【问题标题】:"Bug" in if statement parameters Learn Ruby The Hard Wayif 语句参数中的“错误”Learn Ruby The Hard Way
【发布时间】:2015-06-01 05:49:13
【问题描述】:

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

【问题讨论】:

标签: ruby if-statement


【解决方案1】:

您可以在这里使用正则表达式。 \d 表示任意数字,+ 表示一次或多次,=~ 是模式匹配运算符,所以:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多