What does “+=” (plus equals) mean?

前端 未结 4 1075
滥情空心
滥情空心 2020-12-09 01:43

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

相关标签:
4条回答
  • 2020-12-09 02:15

    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"
    
    0 讨论(0)
  • 2020-12-09 02:31

    += is a shorthand operator.

    someVar += otherVar
    

    is the same as

    someVar = someVar + otherVar
    
    0 讨论(0)
  • 2020-12-09 02:39

    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.

    0 讨论(0)
  • 2020-12-09 02:39

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

    0 讨论(0)
提交回复
热议问题