This article uses Ruby 2.6.3 installed on macOS.
I made a note of how to solve the Ruby super-introduction exercise (p176) that can be understood from scratch. At first, I couldn't solve it this way because I thought that the key was written as a symbol. I felt that I needed the ability to determine where to use hashes.
Q: There are two menus, coffee 300 yen and cafe latte 400 yen. The size is +0 yen for short, +50 yen for tall, and +100 yen for venti. Take an order using the method.
Version that can be ordered from the terminal
def price
puts "What would you like to order?"
item = gets.chomp
puts "What size do you want?"
size = gets.chomp
items = {"coffee" => 300, "Latte" => 400}
sizes = {"short" => 0, "Thor" => 50, "Venti" => 100}
total = items[item] + sizes[size]
puts "#{total}It will be a circle"
end
price
How to use keyword arguments and default values (almost the same as the answer in the book)
def price(item: "coffee", size: "Thor")
items = {"coffee" => 300, "Latte" => 400}
sizes = {"short" => 0, "Thor" => 50, "Venti" => 100}
items[item] + sizes[size]
end
puts price(item: "Latte", size: "Venti")
Recommended Posts