Search code examples
arraysrubyactivesupport

Array method versus hashes


I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]

but it fails with hashes:

Array({a: 1}) # => [[:a, 1]]

which should be [{:a=>1}].

Alternatively, I could add a type check:

responses = [responses] if responses.is_a?(Hash)

Is there a better solution?


Solution

  • ActiveSupport introduces Array#wrap that does exactly what you want:

    Array.wrap(responses)
    

    I personally prefer to never use any Rails helpers for many reasons, so I would stick with [responses].flatten, or, even better, with the most explicit version:

    case responses
    when Hash then [responses]
    when Array then responses
    else raise "shit happened"
    end