Ruby Assignment Operators

Why is the operator operator added while the assignment operator + = not?

Why do operators work this way:

ruby-head> 2. + (4)
=> 6

While assignment operators work as follows:

ruby-head> i = 1
=> 1
ruby head> i + = 1
=> 2
ruby-head> i. + = (1) SyntaxError: (irb): 26: syntax error, unexpected '=' i. + = (1) ^ from /Users/fogonthedowns/.rvm/rubies/ruby-head/bin/irb:17:in ``

+3
source share
3 answers

Since assignment does not work with variables with objects and, therefore, cannot be implemented as a method.

+11
source

+ = ( ) , +. - , +:

class CustomPlus
  attr_accessor :value
  def initialize(value)
    @value = value
  end
  def +(other)
    value + other * 2
  end
end

:

ruby-1.9.1-p378 > a = CustomPlus.new(2)
 => #<CustomPlus:0x000001009eaab0 @value=2> 
ruby-1.9.1-p378 > a.value
 => 2 
ruby-1.9.1-p378 > a+=2
 => 6 
+1

Because it +=is simply a shorthand for full expression.

If this was the message itself, then adding operator behavior for the class would require defining an assignment operator for each of the shortened combinations, in addition to the already probably necessary operators for simple assignment and each binary operator.

It is hard to imagine what would have happened for all this extra work, so Ruby treats the combined assignment operators simply as a shorthand for the full expression.

0
source

Source: https://habr.com/ru/post/1782970/


All Articles