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"
Author by
F F
Updated on September 13, 2020Comments
-
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 over 12 yearsThanks alot for your help I appreciate the speedy answer.
-
oligan over 12 yearsAnd
someVar = someVar + otherVar
is the same assomeVar = someVar.+(otherVar)
. Feel free to write your own class and implement+
on it, and you, too, can have the+=
magic! -
rdvdijk over 11 yearsNote that you (probably) need to return
self
in your+
function to make+=
work as expected. -
Mike H-R over 10 yearsI've got something a little more advanced that I wanted to ask here Can people explain the difference between
a*=b
anda=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 over 10 years@MikeH-R - It looks like you already have the answer - order of operations.