0

我有一个哈希数组,如下所示:

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 }
4

3 回答 3

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"}]
于 2017-11-05T15:51:08.077 回答
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使用to 8.00call更新记录:

items[1] = '8.00'

或者,如果您需要知道项目的数量,您可能需要考虑这样的结构:

items = { 1 => ['2.00', 4], 2 => ['6.00', 1] }

比这样更新:

items[1][0] = '8.00'
于 2017-11-05T15:23:35.687 回答
2

您可以通过使用 each on array 来实现这一点

items.each{|v| v["cost"] = "8.00" if v["id"] == 1 }

干杯!

于 2017-11-05T15:35:58.690 回答