I am trying to understand string concatenation.
Why doesn't the fourth line give the same result as the second one?
counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"
I am trying to understand string concatenation.
Why doesn't the fourth line give the same result as the second one?
counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"
++
just looks like the increment operator. It's actually two unary +
operators, so it's just the same as plain old counter
Because, ++
is not an operator for Ruby like C or Java.
There is no ++
operator in Ruby. What ++counter
says is "give me the positive result of the positive result of 0" which is 0.
++
is not an operator in Ruby. If you want to use a pre-increment operator then use:
counter += 1
In Ruby, ++x
or --x
will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ......
or +x == +++x == +++++x == ......
To increment a number, simply write x += 1
.
To decrement a number, simply write x -= 1
.
Proof :
x = 1
+x == ++++++x # => true
-x == -----x # => true
x # => 1 # value of x doesn't change.
In C
++counter //Pre Increment
counter++// Post Incremet
But In Ruby ++ has no existence ,
So if you want to increment a variable then you have to simply write
counter = counter + 1
In your case you have to write just
"#{counter = counter + 1}. test" gives "1. test"
And will increment the value counter by 1