简体   繁体   中英

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 . 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?

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:

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

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

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM