Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 字符串连接?_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 字符串连接?

Ruby on rails 字符串连接?,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我试图理解字符串连接 为什么第四行的结果与第二行的结果不一样 counter = 0 "#{counter+1}. test" gives "1. test" counter = 0 "#{++counter}. test" gives "0. test" 因为,++不像C或Java那样是Ruby的操作符。Ruby中没有++操作符。++counter所说的是“给我0的正结果的正结果”,即0。++看起来就像递增运算符。它实际上是两个一元的+运算符,因此它与普通的老式计数器一样+在Ruby中不是运

我试图理解字符串连接

为什么第四行的结果与第二行的结果不一样

counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"

因为,
++
不像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==++x==++x==..

要增加一个数字,只需写
x+=1

要减小一个数字,只需写
x-=1

证明:

x = 1
+x == ++++++x # => true
-x == -----x # => true
x # => 1 # value of x doesn't change.

同样的结果或不同的结果,而且ruby不支持
++
操作符也请看这个答案:我只是问了一个问题,关于这个问题,我很好奇:它还说明了如何重新定义一元
++
操作符,这可能有助于解释它存在的原因。