开发者

Ruby Assignment Operators

Why is the addition "operator" a method while the assignment operator += not?

Why do operators work this way:

ruby-head > 2.+(4)

=> 6

While assignment operators work this way:

ruby-head > i = 1

=> 1

ruby-head > i += 1

=> 2

ru开发者_高级运维by-head > i.+=(1) SyntaxError: (irb):26: syntax error, unexpected '=' i.+=(1) ^ from /Users/fogonthedowns/.rvm/rubies/ruby-head/bin/irb:17:in `'


Because assignment works on variables not objects and thus cannot be implemented as a method.


The += is (as I conjectured) syntactic sugar that uses the + method. If you subclass or monkey-patch a class to change the behaviour of +:

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

Then the result is this:

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 


Because += is just a shorthand for the full expression.

If it were a message of its own, then adding operator behavior for a class would require defining an assignment operator for each of the shorthand combinations, in addition to the already-probably-required operators for plain assignment and each binary operator.

It's hard to imagine what would be gained for all that extra work, so Ruby treats the combined assignment operators simply as shorthand for the full expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜