我的 Rails 应用程序今天才开始收到此错误。这是代码上下文。它在以开头的行抛出错误new_host_id
while @host_ids.include?(new_host_id)
i++
new_host_id = duplicate_host_id + i.to_s
end
我的 Rails 应用程序今天才开始收到此错误。这是代码上下文。它在以开头的行抛出错误new_host_id
while @host_ids.include?(new_host_id)
i++
new_host_id = duplicate_host_id + i.to_s
end
Ruby 没有运算符++
。
Ruby 中的成语i += 1
是 . 的缩写形式i = i + 1
。
最初我认为发布的代码不正确,必须++i
生成该错误。然而,正如 Jörg W Mittag 在评论中解释的那样,情况并非如此:
[..] Ruby 允许在运算符和操作数之间使用空格(包括换行符),因此整个事情被解释为
i + (+(new_host_id = duplicate_host_id + i.to_s))
[.. 这就是为什么 NoMethodError 指的是字符串。
这是一个显示问题的简化示例(发布的代码是指第一种情况):
> x =“你好” > +x "hello" 的未定义方法 `+@':String (NoMethodError) > x+ 语法错误,意外 $end
我使用+
and not ++
above 来简化示例:Ruby 将++i
andi++
视为产品+(+i)
和 [大致] i+(+)
..
原来错误是由上一行引起的i++
我改成现在它正在工作i++
。i = i + 1
这是工作代码
while @host_ids.include?(new_host_id)
i = i + 1
new_host_id = duplicate_host_id + i.to_s
end
如果您有警告,您可能会收到关于该行的警告。
$VERBOSE = true
def foo
i = 2
i++
j = 5
j + i
end
warning: possibly useless use of + in void context