What does "+=" (plus equals) mean?

75,970

Solution 1

+= is a shorthand operator.

someVar += otherVar

is the same as

someVar = someVar + otherVar

Solution 2

Not an ruby expert but I would think that it either appends to an existing String or increments an numeric variable?

Solution 3

You should look for a good book about Ruby, e.g. http://pragprog.com/book/ruby3/programming-ruby-1-9

The first 150 pages cover most of the basic things about Ruby.

str = "I want to learn Ruby"

i = 0
str.split.each do |word|
  i += 1
end

puts "#{i} words in the sentence \"#{str}\""

  => 5 words in the sentence "I want to learn Ruby"
Share:
75,970
F F
Author by

F F

Updated on September 13, 2020

Comments

  • F F
    F F over 3 years

    I am doing some ruby exercises and it said I need to go back and rewrite the script with += shorthand notations.

    This exercise deals primarily with learning new methods. The problem is, I have no idea what += means when I tried to look it up online.

  • F F
    F F over 12 years
    Thanks alot for your help I appreciate the speedy answer.
  • oligan
    oligan over 12 years
    And someVar = someVar + otherVar is the same as someVar = someVar.+(otherVar). Feel free to write your own class and implement + on it, and you, too, can have the += magic!
  • rdvdijk
    rdvdijk over 11 years
    Note that you (probably) need to return self in your + function to make += work as expected.
  • Mike H-R
    Mike H-R over 10 years
    I've got something a little more advanced that I wanted to ask here Can people explain the difference between a*=b and a=a*b (see link for more details) I had assumed they were the same although this doesn't appear to be the case.
  • Justin Niessner
    Justin Niessner over 10 years
    @MikeH-R - It looks like you already have the answer - order of operations.