Lesson 7 of 10
Defining methods
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Keyword arguments and methods ending in ? or !
Explanation
You define a method with def and close it with end. You don't need return in it, because a method returns the value of the last line it runs. Save return for leaving a method before it reaches the end.
A parameter gets a default value with =, like def total(price, qty = 1). Keyword arguments are written with a colon, like discount: 0, and the caller passes them by name: total(50, 3, discount: 20). That way the line makes sense without looking up the method's definition, and one number can't get mixed up with the one next to it.
Ruby's method names follow conventions that carry meaning. A method whose name ends in ? asks a question and returns true or false, like empty?, and one that ends in ! is the "dangerous" version, which usually changes the object itself. So strip returns a new string, while strip! changes the string itself.
Watch out: many ! methods return nil when there's nothing to change. "VIP".upcase! returns nil, and that's why code.strip!.upcase! crashes as soon as it gets a string with no spaces to strip. Use ! only to change the variable itself, and don't rely on the value it returns.
Your task
Define total(price, qty = 1, discount: 0) to return the price times the quantity minus the discount, free_shipping?(amount) to return true when the amount is 200 or more, and normalize(code) to return the string with no spaces and in upper case, without changing the string passed to it. Then clean up coupon itself with strip! and upcase!.
Checks
6 checks- total works with the default quantity of 1 and no discount
- total works with a quantity and a keyword discount
- free_shipping? returns true or false
- normalize returns a new string and leaves the original alone
- normalize works with a string that's already clean
- coupon itself was cleaned up with ! methods