Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of hashes to hash

Tags:

arrays

ruby

hash

For example, I have array of single hashes

a = [{a: :b}, {c: :d}] 

What is best way to convert it into this?

{a: :b, c: :d} 
like image 510
evfwcqcg Avatar asked Jun 08 '12 06:06

evfwcqcg


People also ask

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

Is an array a hash?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.

How do you create an array of hashes in Ruby?

Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

How do you merge hashes in Ruby?

Hash#merge!() is a Hash class method which can add the content the given hash array to the other. Entries with duplicate keys are overwritten with the values from each other_hash successively if no block is given.


2 Answers

You may use

a.reduce Hash.new, :merge 

which directly yields

{:a=>:b, :c=>:d} 

Note that in case of collisions the order is important. Latter hashes override previous mappings, see e.g.:

[{a: :b}, {c: :d}, {e: :f, a: :g}].reduce Hash.new, :merge   # {:a=>:g, :c=>:d, :e=>:f} 
like image 158
Howard Avatar answered Oct 13 '22 20:10

Howard


You can use .inject:

a.inject(:merge) #=> {:a=>:b, :c=>:d} 

Demonstration

Which initiates a new hash on each iteration from the two merged. To avoid this, you can use destructive :merge!( or :update, which is the same):

a.inject(:merge!) #=> {:a=>:b, :c=>:d} 

Demonstration

like image 22
potashin Avatar answered Oct 13 '22 20:10

potashin