How do I replace age with 31?
[{"name"=>"Bob"}, {"age"=>"30"}]
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}]
Why not convert the array into something easier and more flexible to work with? Your array is crying out to be a value object:
class Person
attr_accessor :name, :age
def initialize arr
arr.each { |h| h.each { |k,v| instance_variable_set("@#{k}", v) } }
end
def to_hash_array
instance_variables.each_with_object([]) do |iv, arr|
arr << {iv.to_s.sub('@','') => instance_variable_get(iv)}
end
end
end
def hash_array_to_person arr
person = Person.new
arr.each { |h| h.each { |k,v| person.send("#{k}=", v) } }
person
end
example = [{"name"=>"Bob"}, {"age"=>"30"}]
bob = Person.new(example)
p bob
p bob.to_hash_array
bob.age = 31
p bob.to_hash_array
Output:
#<Person:0x00000000fe8418 @name="Bob", @age="30">
[{"name"=>"Bob"}, {"age"=>"30"}]
[{"name"=>"Bob"}, {"age"=>31}]
Ruby isn't C, you have so much more available to you than the basic primitive data types.
Since what you really have is an array of hashes, you can index the array to get the second hash and then update the value by passing "age" as the key:
1.9.3p194 :001 > h = [{"name"=>"Bob"}, {"age"=>"30"}]
=> [{"name"=>"Bob"}, {"age"=>"30"}]
1.9.3p194 :002 > h[1]["age"] = 31
=> 31
1.9.3p194 :003 > h
=> [{"name"=>"Bob"}, {"age"=>31}]
[{"name"=>"Bob", "age"=>"30"}]