【问题标题】:Why is include? throwing an argument error?为什么是包含?抛出参数错误?
【发布时间】:2013-06-08 16:57:24
【问题描述】:

这是一大段代码的 sn-p:

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

此代码昨晚在另一台计算机上运行。

include? 不是在检查那个全局变量的内容吗?我应该向它传递什么其他参数?

我有点难过,尤其是因为我所做的只是将代码从一台计算机移动到另一台计算机。

【问题讨论】:

  • "此代码昨晚在另一台计算机上运行。"错误……不。 :-) 很可能,case "next_move".include? "instructions" 做了,或者case "next_move" when "instructions"
  • 使用全局变量时要非常小心:$next_move。在 Ruby 代码中很少需要它们,而且在大多数情况下,它们是您做错了什么的警告信号。
  • @tinman,谢谢。我已经改进了我的编码以避免它们。这是几周前的一个练习,至今仍让我感到困惑。尽管丹尼斯不相信我,但老实说,我所做的只是在另一台计算机上运行代码,突然之间,那些有效的东西似乎不再有效......

标签: ruby arguments


【解决方案1】:

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-include-3F

如果 str 包含给定的字符串或字符,则返回 true。

这意味着它只需要 1 个参数,所以难怪在不带参数的情况下调用它会抛出 ArgumentError。

所以代码应该是:

if $next_move.include? 'instructions'
  puts '$next_move is instructions'
else
  puts '$next move is NOT instructions'
end

【讨论】:

  • "此外,您调用 include? 不是在 next_move 变量中包含的字符串上,而是在字符串 'next_move' 上。"嗯?这是如何运作的?我怎么不调用变量的内容?
  • 您在问题的第一个版本中就做到了。
【解决方案2】:

在您测试的两台计算机之间必须发生一些变化。如果您想将此用作案例陈述,您可能有以下内容:

next_move = 'instructions'

case next_move
when "instructions"
  puts "$next_move is instructions"
else
  puts "$next_move is NOT instructions"
end

这专门测试next_move IS 指令。作为 if/else 语句:

if next_move.include? 'instructions'
  puts "$next_move is instructions"
else
  puts "$next_move is NOT instructions"
end

更多信息请参见eval.in

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2019-12-16
    • 2018-08-19
    相关资源
    最近更新 更多