我想了解字符串連接。字符串連接?
爲什麼第四行的結果不如第二行?
counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"
我想了解字符串連接。字符串連接?
爲什麼第四行的結果不如第二行?
counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"
++
只是看起來像增量算子。它實際上是兩個一元運算符+
,所以它就像普通老counter
因爲++
不是像C或Java這樣的Ruby運算符。
Ruby中沒有++
運算符。 ++counter
所說的是「給我0的正面結果的正面結果」,它是0.
++
不是Ruby中的運算符。如果你想使用一個預先遞增運算符,然後使用:
counter += 1
在C
++counter //Pre Increment
counter++// Post Incremet
但是在Ruby ++沒有存在,
所以如果你想增加一個變量,那麼你必須簡單地寫
counter = counter + 1
你的情況,你必須寫只是
"#{counter = counter + 1}. test" gives "1. test"
而且會增加值計數器通過
在Ruby中,++x
或--x
會做什麼!事實上,它們表現爲多一元前綴運營商:或+x == +++x == +++++x == ......
要增量一個號碼,只需寫x += 1
。
要遞減一個號碼,只需寫x -= 1
。
證明:
x = 1
+x == ++++++x # => true
-x == -----x # => true
x # => 1 # value of x doesn't change.
結果相同或不同的結果,而且紅寶石不支持''+運營商 – bjhaid
看到這個答案還有:http://stackoverflow.com/questions/5680587/whats-一元加運營商在紅寶石 –
剛剛問了一個問題,進入這個我很好奇的一點細節:http://stackoverflow.com/questions/22085607/ruby-unary -operator-behavior它還說明了如何重新定義一元''''操作符,它可能會對它存在的原因略有介紹。 – JKillian