我有一系列哈希如下:
items = [ {"id" => 1, "cost" => '2.00'},
{"id" => 2, "cost" => '6.00'},
{"id" => 1, "cost" => '2.00'},
{"id" => 1, "cost" => '2.00'},
{"id" => 1, "cost" => '2.00'} ]
我想更新cost to '8.00'
所在的id = 1
。我尝试使用下面的each
方法,但是我想知道是否还有另一种更有效的方法来更新值?
items.each { |h| h["cost"] = "8.00" if h["id"] == 1 }
答案 0 :(得分:3)
您可以使用相同的对象:
item_1 = {'id' => 1, 'cost' => '2.00'}
item_2 = {'id' => 2, 'cost' => '6.00'}
items = [item_1, item_2, item_1, item_1, item_1]
#=> [{"id"=>1, "cost"=>"2.00"}, {"id"=>2, "cost"=>"6.00"},
# {"id"=>1, "cost"=>"2.00"}, {"id"=>1, "cost"=>"2.00"},
# {"id"=>1, "cost"=>"2.00"}]
这会使更新变得微不足道:
item_1['cost'] = '8.00'
items
#=> [{"id"=>1, "cost"=>"8.00"}, {"id"=>2, "cost"=>"6.00"},
# {"id"=>1, "cost"=>"8.00"}, {"id"=>1, "cost"=>"8.00"},
# {"id"=>1, "cost"=>"8.00"}]
答案 1 :(得分:2)
您可以考虑更改数据结构:
items = [{"id" => 1, "cost" => '2.00'}, {"id" => 2, "cost" => '6.00'},
{"id" => 1, "cost" => '2.00'}, {"id" => 1, "cost" => '2.00'},
{"id" => 1, "cost" => '2.00'}]
像这样的哈希:
items = { 1 => '2.00', 2 => '6.00' }
要使用id = 1
至8.00
来更新记录:
items[1] = '8.00'
或者如果您需要知道项目数量,您可能需要考虑这样的结构:
items = { 1 => ['2.00', 4], 2 => ['6.00', 1] }
比这更新:
items[1][0] = '8.00'
答案 2 :(得分:2)
您可以通过在数组
上使用每个来实现此目的items.each{|v| v["cost"] = "8.00" if v["id"] == 1 }
干杯!