将值更新为 ruby 中的哈希数组的有效方法?
Efficient way to update values to array of hashes in ruby?
我有一个哈希数组,如下所示:
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 }
您可以考虑更改您的数据结构:
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'
您可以通过在数组上使用 each 来实现此目的
items.each{|v| v["cost"] = "8.00" if v["id"] == 1 }
干杯!
您可以只使用同一个对象:
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"}]
我有一个哈希数组,如下所示:
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 }
您可以考虑更改您的数据结构:
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'
您可以通过在数组上使用 each 来实现此目的
items.each{|v| v["cost"] = "8.00" if v["id"] == 1 }
干杯!
您可以只使用同一个对象:
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"}]