How to combine array values ​​with hash array?

I have an array of hashes:

[{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4} ...] 

And an array of integers:

 [3, 6] 

I want to combine the values ​​from an integer array and hashes, so that in the end I get something like:

 [{:foo => 1, :bar => 2, :baz => 3}, {:foo => 2, :bar => 4, :baz => 6}] 

I am currently doing this:

 myArrayOfHashes.each_with_index |myHash, index| myHash[:baz] = myArrayOfIntegers[index] end 

Is this the right approach?

I imagined a more functional approach when I repeat both arrays at the same time, somehow using zip + map .

+4
source share
3 answers

Try:

 require 'pp' ary_of_hashes = [{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4}] [3, 6].zip(ary_of_hashes).each do |i, h| h[:baz] = i end pp ary_of_hashes 

Result:

 [{:foo=>1, :bar=>2, :baz=>3}, {:foo=>2, :bar=>4, :baz=>6}] 

zip is a good tool for this, but map will not buy much, at least nothing that you could not do so easily with each in this case.

Also, don't name variables with CamelCase, like myArrayOfHashes , use snake_case like ary_of_hashes . We use CamelCase for class names. Technically, we can use the mixed case for variables, but by convention we do not.

And it is possible to use each_with_index , but this leads to inconvenient code, because it forces you to use the index in [3, 6] . Let zip join the corresponding elements of both arrays and you will have everything you need to massage the hash.

+6
source

map is useful if you want to leave the original objects intact:

 a = [{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4}] b = [3,6] a.zip(b).map { |h, i| h.merge(baz: i) } # => [{:foo=>1, :bar=>2, :baz=>3}, {:foo=>2, :bar=>4, :baz=>6}] a.inspect # => [{:foo=>1, :bar=>2}, {:foo=>2, :bar=>4}] 
+6
source
 array_of_hashes.each { |hash| hash.update baz: array_of_integers.shift } 
+3
source

Source: https://habr.com/ru/post/1487419/


All Articles