Accepting either a hash or an array of hashes as arguments to a Ruby method

Viewed 2899

I have the method:

def self.store(params)
  params.each { }
end

It works perfectly, if I pass an Array of Hashes:

params = [ { key: 'value' }, { key: 'value' } ]

However, I might want to pass only a single Hash, instead of an Array of Hashes:

params = { key: 'value' }

What would be the cleanest Ruby way to convert a Hash into an Array of Hashes?

The Array() method a kind of ensures, that an array is always returned, but when the Hash is passed, it is converted into an Array itself.

Array({ key: 'value' }) => [[:key, 'value']]

What I need:

 { key: 'value' } => [ { key: 'value' } ]

Is there any nice way to implement this, or do I have to do a manual type checking with is_a?(Array) ?

3 Answers
Related