Reputation: 59
On line 7 of http://learnrubythehardway.org/book/ex35.html, there is a comment stating there is a bug.
When this program runs and you choose a number which contains, neither a "0" nor a "1" it will say it's not a number. How do I get it to detect all numbers?
Here is the code:
def gold_room
puts "This room is full of gold. How much do you take?"
print "> "
choice = $stdin.gets.chomp
# this line has a bug, so fix it
if choice.include?("0") || choice.include?("1")
how_much = choice.to_i
else
dead("Man, learn to type a number.")
end
if how_much < 50
puts "Nice, you're not greedy, you win!"
exit(0)
else
dead("You greedy bastard!")
end
end
Upvotes: 0
Views: 703
Reputation: 15791
You can use regular expression here. \d
means any digit, +
means one or more times, =~
is a pattern match operator, so:
if choice =~ /\d+/
how_much = choice.to_i
else
dead("Man, learn to type a number.")
end
Upvotes: 6