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 }
n(n=> the number of elements in the array) steps in the worst case. A more efficient way would be a different data structure - for example a hash with the id being the key and the value being the cost. That would take exactly one step to find the element to update. Is using a hash instead of an array with nested hashes an option?N + 1 eachmethod and I would like to know any method which should be efficient. So please feel free use a hash