我的Rails應用程序剛剛開始接收此錯誤,今天。這是代碼上下文。這是投擲啓動與new_host_id
NoMethodError:未定義的方法`+ @'爲「有些刺痛」:字符串
while @host_ids.include?(new_host_id)
i++
new_host_id = duplicate_host_id + i.to_s
end
我的Rails應用程序剛剛開始接收此錯誤,今天。這是代碼上下文。這是投擲啓動與new_host_id
NoMethodError:未定義的方法`+ @'爲「有些刺痛」:字符串
while @host_ids.include?(new_host_id)
i++
new_host_id = duplicate_host_id + i.to_s
end
紅寶石確實不有++
運營商。
Ruby中的成語是i += 1
,這是i = i + 1
的縮寫形式。
起初我以爲貼碼不正確,必須是++i
生成錯誤。然而,如約爾格W¯¯米塔格在註釋解釋,不是這種情況:
[..] Ruby allows whitespace (including line breaks) between an operator and the operand(s), so the entire thing is interpreted as
i + (+(new_host_id = duplicate_host_id + i.to_s))
[.. which is] why the NoMethodError refers to String.
下面是該問題的簡化示例(張貼的代碼是指第一種情況):
> x = "hello" > +x undefined method `[email protected]' for "hello":String (NoMethodError) > x+ syntax error, unexpected $end
我用+
以及上面沒有++
簡化示例:紅寶石對待++i
和i++
作爲製作+(+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
不,這是正確的。 Ruby允許運算符和操作數之間有空格(包括換行符),所以整個事物被解釋爲'i +(+(new_host_id = duplicate_host_id + i.to_s))'或類似的東西。這就是爲什麼'NoMethodError'引用'String'的原因。 – 2012-07-17 00:53:12
@JörgWMittag謝謝,我不能相信我錯過了。 – 2012-07-17 01:45:00
感謝您的解釋。我很好奇爲什麼i ++在生產環境中工作2個月才發生錯誤... – Paul 2012-07-17 02:32:11