Search code examples
arraysrubyruby-hash

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 }

Solution

  • 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"}]