If you would like to stick with arrays, then try something like:
arr1 = [['Area1', 12345], ['Area2', 54321]]
arr2 = ['Area1', 33441]
arr1.inject([]){|r,i| r.push(i[0] == arr2[0] ? i.push(arr2[1]) : i)}
In console:
2.3.1 :001 > arr1 = [['Area1', 12345], ['Area2', 54321]]
=> [["Area1", 12345], ["Area2", 54321]]
2.3.1 :002 > arr2 = ['Area1', 33441]
=> ["Area1", 33441]
2.3.1 :003 > arr1.inject([]){|r,i| r.push(i[0] == arr2[0] ? i.push(arr2[1]) : i)}
=> [["Area1", 12345, 33441], ["Area2", 54321]]
Looking at polmiro's answer, I prefer his map
to my inject
. They are essentially the same, I believe. Except that map
does the work for you of creating a new array
whereas with inject
you have to pass in the new array
. And, map
is doing an implicit push
whereas, with inject
, again, you have to do the work yourself. Nice job, polmiro!
Here's the one-line version of his answer (if you like that sort of thing):
arr1.map{|a| a[0] == arr2[0] ? a << arr2[1] : a}
And again in console:
2.3.1 :001 > arr1 = [['Area1', 12345], ['Area2', 54321]]
=> [["Area1", 12345], ["Area2", 54321]]
2.3.1 :002 > arr2 = ['Area1', 33441]
=> ["Area1", 33441]
2.3.1 :003 > arr1.map{|a| a[0] == arr2[0] ? a << arr2[1] : a}
=> [["Area1", 12345, 33441], ["Area2", 54321]]