if语句参数中的"Bug"学习Ruby The Hard Way

lag*_*nio 0 ruby if-statement

http://learnrubythehardway.org/book/ex35.html的第7行,有一条评论说明有一个错误.

当这个程序运行并且您选择一个包含的数字时,既不是"0"也不是"1",它会说它不是数字.如何让它检测所有数字?

这是代码:

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
Run Code Online (Sandbox Code Playgroud)

Rus*_*nov 6

你可以在这里使用正则表达式.\d表示任何数字,+表示一次或多次,=~是模式匹配运算符,因此:

if choice =~ /\d+/
  how_much = choice.to_i
else
  dead("Man, learn to type a number.")
end
Run Code Online (Sandbox Code Playgroud)