比方说,我有一个这样的集合:
[{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2}...]
如何将集合中所有magic_numbers的值更改为相同的值(例如8)?
我确定它正在使用地图或收集之类的东西,但我现在似乎无法做到这一点并将整个收藏集返回给我,只是其中一个......
答案 0 :(得分:3)
只需使用.each
:
a = [{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2} ]
a.each { |x| x['magic_number'] = 8 }
# a is now [{"magic_number"=>8, "name"=>"Ganesh"}, {"magic_number"=>8, "name"=>"Comrade"}]
块的参数是对原始元素的引用,因此您可以根据需要更改它们。请注意,这会改变a
就地,我认为这就是您所追求的目标。
答案 1 :(得分:1)
这有效:
x = [{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2}]
x.map{|i| i["magic_number"] = 0; i }
=> [{"magic_number"=>0, "name"=>"Ganesh"}, {"magic_number"=>0, "name"=>"Comrade"}]