How can I improve my Ruby practices with array and hash? -
I have array1
, which is an array of hash, and array2
, which is an array of integers array1.size
and array2.size
are 10
. I want to add each element in the corresponding hash array1
in array 2
. Then array2 [0]
will be added to the array1 [0]
in the hash.
I've coded it:
0 in 0 array1.size array 1 [x] [: array2_value] = array2 [x] end
I think there is a clear way to do this. Any help would be appreciated.
One way:
array1.each_with_index {| H, i | H [: array2_value] = array2 [i]}
Other:
array1.zip (array2) .each {| H, v | H [: array2_value] = v}
If array1
is not to change:
array1.map.with_index {| H, i H [: array2_value] = array 2 [i]} array1.zip (array2) .map {| H, v | H [: array2_value] = v}
Comments
Post a Comment