Ruby 为什么要包括?抛出参数错误?
这是一段较大的代码片段:Ruby 为什么要包括?抛出参数错误?,ruby,arguments,Ruby,Arguments,这是一段较大的代码片段: print "> " $next_move = gets.chomp case $next_move.include? when "instructions" puts "$next_move is instructions" else puts "$next_move is NOT instructions" end 每次我在终端中运行它时,无论我使用的是ruby 1.8.7、1.9.3还是2.0.0,都会出现以下错误: test.rb:4:in `
print "> "
$next_move = gets.chomp
case $next_move.include?
when "instructions"
puts "$next_move is instructions"
else
puts "$next_move is NOT instructions"
end
每次我在终端中运行它时,无论我使用的是ruby 1.8.7、1.9.3还是2.0.0,都会出现以下错误:
test.rb:4:in `include?': wrong number of arguments (0 for 1) (ArgumentError)
from test.rb:4
这段代码昨晚在另一台计算机上运行
是否包含?
检查该全局变量的内容?我还应该传递什么样的论点
我在这里有点困惑,尤其是因为我所做的只是将代码从一台计算机移动到另一台计算机。
如果str包含给定的字符串或字符,则返回true
这意味着它只需要1个参数,所以在没有参数的情况下调用时抛出ArgumentError也就不足为奇了
因此,代码应该是:
if $next_move.include? 'instructions'
puts '$next_move is instructions'
else
puts '$next move is NOT instructions'
end
你测试的两台计算机之间一定发生了变化。如果您想将此作为案例陈述,您可能有以下几点:
next_move = 'instructions'
case next_move
when "instructions"
puts "$next_move is instructions"
else
puts "$next_move is NOT instructions"
end
这专门测试next\u move
是否为指令。作为if/else语句:
if next_move.include? 'instructions'
puts "$next_move is instructions"
else
puts "$next_move is NOT instructions"
end
有关更多信息,请参阅。“此代码昨晚在另一台计算机上工作。”错误。。。否:-)可能是“下一步”。包括?“指令”已执行,或在“指令”时使用“下一步”的大小写。使用全局变量时要非常小心:
$next\u move
。Ruby代码中很少需要它们,而且大多数情况下,它们是一个警告信号,表明您做错了什么。@tinman,谢谢。此后,我改进了编码以避免它们。这是几周前的一个练习,至今仍让我感到困惑。尽管Denis不相信我,但老实说,我所做的只是在另一台计算机上运行代码,突然间,工作起来的东西似乎不再工作了……”“此外,你调用include?不是在next_move变量中包含的字符串上,而是在字符串‘next_move’上。”?这是怎么回事?我怎么能不调用变量的内容呢?你在问题的第一个版本中就这么做了。