0

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"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ssinganamalla
  • 1,250
  • 3
  • 12
  • 19
  • 2
    same result or different results, moreover ruby does not support the `++` operator – bjhaid Feb 28 '14 at 03:18
  • 1
    See this answer as well: http://stackoverflow.com/questions/5680587/whats-the-point-of-unary-plus-operator-in-ruby – Zach Kemp Feb 28 '14 at 03:20
  • Just asked a question going into a little more detail on this that I'm curious about: http://stackoverflow.com/questions/22085607/ruby-unary-operator-behavior It also illustrates how you can redefine the unary `+` operator which might shed a little light on why it exists. – JKillian Feb 28 '14 at 03:30

6 Answers6

3

++ just looks like the increment operator. It's actually two unary + operators, so it's just the same as plain old counter

JKillian
  • 18,061
  • 8
  • 41
  • 74
2

Because, ++ is not an operator for Ruby like C or Java.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Masudul
  • 21,823
  • 5
  • 43
  • 58
2

There is no ++ operator in Ruby. What ++counter says is "give me the positive result of the positive result of 0" which is 0.

Zach Kemp
  • 11,736
  • 1
  • 32
  • 46
2

++ is not an operator in Ruby. If you want to use a pre-increment operator then use:

counter += 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36
2

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.
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1

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

Arjun
  • 815
  • 1
  • 8
  • 18