有效的方法将值更新为ruby中的哈希数组?

时间:2017-11-05 15:05:33

标签: arrays ruby ruby-hash

我有一系列哈希如下:

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 }

3 个答案:

答案 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 = 18.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 }

干杯!