2012-11-16 97 views

回答

5

另一種方法,使用發現

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}] 
2

既然你真的有是哈希的數組,你可以索引數組,以獲得第二哈希值,然後通過傳遞"age"作爲關鍵更新值:

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}] 
1

這樣做:

[{"name"=>"Bob"}, {"age"=>"30"}][1]["age"] = 31 
3

爲什麼不將數組轉換成更簡單,更靈活的數組?你的陣列是哭出來的是一個值對象:

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 

輸出:

#<Person:0x00000000fe8418 @name="Bob", @age="30"> 
[{"name"=>"Bob"}, {"age"=>"30"}] 
[{"name"=>"Bob"}, {"age"=>31}] 

Ruby是不是C,你有這麼比基本的原始數據類型,更提供給您。