Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ?

like image 973
krn Avatar asked Aug 13 '12 17:08

krn


People also ask

How do you hash an array in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

How do you make hash hashes in Ruby?

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

How do you add two hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.


2 Answers

For me, the best solution is to change the method to:

def self.store(*hashes)
  params = hashes.flatten
  puts params.inspect
end
  • If you pass a single hash, it will be an array
  • If you pass an array of hashes, it remains the same
  • If you pases N hashes, it compacts all parameters into a one dimensional array.

You can pass whatever you want.

self.store({:key => 'value'}) # => [{:key => 'value'}]
self.store({:key => 'value'}, {:foo => 'bar'}) # => [{:key => 'value'}, {:foo => 'bar'}]
self.store([{:key => 'value'}, {:foo => 'bar'}]) # => [{:key => 'value'}, {:foo => 'bar'}]
like image 110
miguel.camba Avatar answered Sep 19 '22 05:09

miguel.camba


Try this

def self.store(params)
  params = [params].flatten
  ...
end
like image 32
Kulbir Saini Avatar answered Sep 18 '22 05:09

Kulbir Saini