35

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.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
F F
  • 391
  • 1
  • 3
  • 6
  • Possible duplicate of [What does "+=" (plus equals) mean in Ruby?](http://stackoverflow.com/questions/10022524/what-does-plus-equals-mean-in-ruby) – Andrew Li Aug 17 '16 at 23:08

4 Answers4

65

+= is a shorthand operator.

someVar += otherVar

is the same as

someVar = someVar + otherVar
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • Thanks alot for your help I appreciate the speedy answer. – F F Oct 03 '11 at 17:32
  • 6
    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! – Andrew Grimm Oct 03 '11 at 22:22
  • Note that you (probably) need to return `self` in your `+` function to make `+=` work as expected. – rdvdijk Dec 21 '12 at 12:56
  • I've got something a little more advanced that I wanted to [ask here](http://stackoverflow.com/questions/20101146/why-does-this-expression-cause-a-floating-point-error) 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. – Mike H-R Nov 20 '13 at 16:21
  • @MikeH-R - It looks like you already have the answer - order of operations. – Justin Niessner Nov 20 '13 at 16:31
15

Expressions with binary operators of the form:

x = x op y

Can be written as:

x op= y

For instance:

x += y   # x = x + y
x /= y   # x = x / y
x ||= y  # x = x || y (but see disclaimer)

However, be warned that ||= and &&= can behave slightly ... different (most evident when used in conjunction with a hash indexer). Plenty of SO questions about this oddity though.

Happy coding.

2

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

chzbrgla
  • 5,158
  • 7
  • 39
  • 56
1

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"
Tilo
  • 33,354
  • 5
  • 79
  • 106