2012-07-16 32 views

回答

8

紅寶石確實++運營商。

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 

我用+以及上面沒有++簡化示例:紅寶石對待++ii++作爲製作+(+i)和[大致] i+(+) ..

+1

不,這是正確的。 Ruby允許運算符和操作數之間有空格(包括換行符),所以整個事物被解釋爲'i +(+(new_host_id = duplicate_host_id + i.to_s))'或類似的東西。這就是爲什麼'NoMethodError'引用'String'的原因。 – 2012-07-17 00:53:12

+0

@JörgWMittag謝謝,我不能相信我錯過了。 – 2012-07-17 01:45:00

+0

感謝您的解釋。我很好奇爲什麼i ++在生產環境中工作2個月才發生錯誤... – Paul 2012-07-17 02:32:11

2

原來的錯誤是由前一行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 
2

我如果你有警告,你可能會對該行發出警告。

$VERBOSE = true 
def foo 
    i = 2 
    i++ 
    j = 5 
    j + i 
end 

warning: possibly useless use of + in void context 
相關問題