[英]Efficient way to update values to array of hashes in ruby?
I have an array of hashes like below: 我有一系列的哈希,如下所示:
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'} ]
I would like to update the cost to '8.00'
where the id = 1
. 我想将
cost to '8.00'
更新cost to '8.00'
,其中id = 1
。 I have tried with the each
method like below which does work but I would like to know if there is another more efficient way of updating the values? 我已经尝试使用下面的
each
方法都可以正常工作,但是我想知道是否还有另一种更有效的更新值的方法?
items.each { |h| h["cost"] = "8.00" if h["id"] == 1 }
You could just use the same object: 您可以只使用同一对象:
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"}]
This makes updates trivial: 这使得更新变得微不足道:
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"}]
You might consider changing your data structure from: 您可以考虑从以下位置更改数据结构:
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'}]
To a hash like this: 像这样的哈希:
items = { 1 => '2.00', 2 => '6.00' }
To updating the record with id = 1
to 8.00
call: 要将
id = 1
的记录更新为8.00
请调用:
items[1] = '8.00'
Or if you need to know the number of items, you might want to conside a structure like this: 或者,如果您需要知道项目数,则可能需要考虑如下结构:
items = { 1 => ['2.00', 4], 2 => ['6.00', 1] }
Than update like this: 比这样更新:
items[1][0] = '8.00'
You can achieve this by using each on array 您可以通过使用每个on数组来实现
items.each{|v| v["cost"] = "8.00" if v["id"] == 1 }
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.