I'm going through a Ruby tutorial and I can't grasp the += statement. Google isn't helping, "Ruby +=" only searches for "Ruby".
Help is appreciated.
Sample:
num = -10
num += -1 if num < 0
puts num
#=> -11
I'm going through a Ruby tutorial and I can't grasp the += statement. Google isn't helping, "Ruby +=" only searches for "Ruby".
Help is appreciated.
Sample:
num = -10
num += -1 if num < 0
puts num
#=> -11
num += -1
is an equivalent of
num = num + -1
or, for this example
num = num - 1
which, in turn, can be written as
num -= 1
It does two things at once.
(1) It adds + 1 to num (2) Assigns back the result to num
Its a shortcut for:
num = num + 1
The segment a += b
is just the short form for a = a + b
. So your statement:
num += -1 if num < 0
will simply subtract one (by adding -1
which is ... quaint, that's probably as polite as I can be) from num
if it is already negative (if num < 0
)..