Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby / Replace value in array of hash

Tags:

ruby

How do I replace age with 31?

[{"name"=>"Bob"}, {"age"=>"30"}]
like image 277
oprogfrogo Avatar asked Nov 16 '12 17:11

oprogfrogo


People also ask

What is Array of hashes in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


1 Answers

Another way, using find

1.9.3p194 :007 > array1 = [{"name"=>"Bob"}, {"age"=>"30"}]
 => [{"name"=>"Bob"}, {"age"=>"30"}] 
1.9.3p194 :008 > hash1 = array1.find { |h| h['age'] == "30" }
 => {"age"=>"30"} 
1.9.3p194 :009 > hash1['age'] = 31
 => 31 
1.9.3p194 :010 > array1
 => [{"name"=>"Bob"}, {"age"=>31}]
like image 200
Dan Polites Avatar answered Oct 07 '22 00:10

Dan Polites