Ruby Hash#transform_values
Calculate a new price for each item on the takeaway menu.
A simple example
Hash#transform_values
- Start with A = 1, B = 2
- Do this Add 1 to each value
- Result A = 2, B = 3
Syntax
prices.transform_values
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbAdd a packing charge to each listed price
A café starts packing takeaway orders in reusable boxes. The manager adds one unit to each listed price and checks the new soup price before publishing the board.
From the programprices = {"Soup" => 4, "Salad" => 6}
Result5
prices = {"Soup" => 4, "Salad" => 6}
revised = prices.transform_values { |price| price + 1 }
puts revised["Soup"]
5
Soup increases from four to five after the packing charge.
Advertisements
Reprint stationery prices
A school shop increases every price by two credits. Every price gets the same increase. Find the revised value for the first item.
GivenPen 7 · increase 2
Worked result9
Revise rental rates
A studio adds a three-credit cleaning fee to every rental. Every price gets the same increase. Find the revised value for the first item.
GivenStand 12 · increase 3
Worked result15
What to watch for
transform_values leaves the original hash intact and calculates a new value for every key.