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 lear
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"
+=
is a shorthand operator.
someVar += otherVar
is the same as
someVar = someVar + otherVar
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.
Not an ruby expert but I would think that it either appends to an existing String or increments an numeric variable?