Exercises from Chapter 9
Improved ask Method
How you could do it:
def ask question |
while true |
puts question |
reply = gets.chomp.downcase |
if reply == 'yes' |
return true |
end |
if reply == 'no' |
return false |
end |
# If we got this far, then we're going to loop |
# and ask the question again. |
puts 'Please answer "yes" or "no".' |
end |
end |
likes_it = ask 'Do you like eating tacos?' |
puts likes_it |
<= | Do you like eating tacos? |
=> | yes |
<= | true |
How I would do it:
def ask question |
while true |
puts question |
reply = gets.chomp.downcase |
return true if reply == 'yes' |
return false if reply == 'no' |
puts 'Please answer "yes" or "no".' |
end |
end |
puts(ask('Do you like eating tacos?')) |
<= | Do you like eating tacos? |
=> | yes |
<= | true |
Old-School ...
Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.