Iterating over a Hash
You can use the each
method to iterate over all the elements in
a Hash. However unlike Array#each
, when you iterate over a Hash using
each
, it passes two values to the block: the key and the value of each element.
Let us see how we can use the each
method to display the restaurant menu.
The restaurant is doing well, but it is forced to raise prices due to increasing costs.
Use the each
method to increase the price of all
the items in the restaurant_menu
by 10%.
Remember: in the previous example we only displayed the keys and values of each item in the hash. But in this exercise, you have to modify the hash and increase the value of each item.
Ideally, any transformation of a collection (like in the example above) should produce a new collection with the original unchanged making the code easier to understand and manage.
However, speed and memory considerations often (and usually wrongly) trump maintainability and so the approach above is used quite frequently.