Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata