2

I am just learning Ruby and I want to know the difference between

a += b 

and

a =+ b 
1
  • 3
    It makes sense, because it is a beginner question. At a guess, the asker saw this in someone else's code (which is why smartypants, non-standard code is rarely a good idea!). Commented Aug 22, 2017 at 10:05

2 Answers 2

6
  1. a += b is syntactic shorthand for a = a + b
  2. a =+ b is similar to a = + b

So, firstValue = firstValue + secondValue is the same as firstValue = firstValue.+(secondValue) in ruby. firstValue + = secondValue – increment Add the value of secondValue to the value of firstValue , store the result in firstValue, and return the new value.

Sign up to request clarification or add additional context in comments.

Comments

4
  • foo += bar is shorthand for foo = foo + bar.
  • foo =+ bar is an unusual way to write foo = +bar.

2 Comments

It’s worth to mention that for the latter to work, the +@ instance method should be defined on bar.class. For the former, the coercion from bar.class to foo.class is required.
An actual use case: if bar is a frozen string, then foo = +bar becomes a shorthand for foo = bar.dup, i.e. it assigns a mutable duplicate of the string to foo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.