4

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
Stn
  • 437
  • 1
  • 6
  • 15
  • `a += 1` is the same as `a = a + 1` `+=` is just a short form. – Ilia Frenkel Apr 05 '12 at 04:06
  • 2
    I _hate_ post-conditions, code should be read like (English) text, left-to-right and downwards. Damn you to perdition, Perl :-) – paxdiablo Apr 05 '12 at 04:09
  • (Try a tutorial; in any case, the keyword is "operator", of which there is a finite set and the rules are well-covered.) –  Apr 05 '12 at 04:24
  • 1
    It should be closed as a duplicate of this: http://stackoverflow.com/questions/7638502/what-does-plus-equals-mean –  Apr 05 '12 at 04:25
  • Try using SymbolHound http://www.symbolhound.com/?q=ruby+%2B%3D – Andrew Grimm Apr 05 '12 at 04:47

3 Answers3

6
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
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Also note that almost any operator can be combined with `=`: `&&=`, `||=`, `&=`, `|=`, `*=`, `/=`, and so on. See "assignment" in [this table from the Pickaxe](http://phrogz.net/programmingruby/language.html#table_18.4). – Andrew Marshall Apr 05 '12 at 05:01
0

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

Benjamin Tan Wei Hao
  • 9,621
  • 3
  • 30
  • 56
0

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)..

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953