Ruby + = overload

What is wrong with this?

class Vec2
  attr_accessor :x, :y
  # ...
  def += (v)
    @x += v.x
    @y += v.y
    return self
  end
  # ...
end

I could not find much online. Someone said that it was because + = a call was made in ruby ​​+, and then =, was he joking correctly?

In a funny case, he was right, is there a workaround (in addition to defining a method called add)?

+3
source share
2 answers

Someone said that it was because + = a call was made in ruby ​​+, and then =, was he joking correctly?

No, he is right (except that "call =" is a little inaccurate, because =it is not a method).

Is there any workaround (besides defining a method called add)?

, +, , += , ?

+, , self, v1 += v2 , v1 + v2, . , , + (, += , ).

, , .

+6

. += - , +. += , :

a = [1, 2, 3]
b = a
b << 4
b += [5, 6, 7]
p a # => [1, 2, 3, 4]
p b # => [1, 2, 3, 4, 5, 6, 7]

a b , << b a. , , += ; , , a .

.

b = a + [5, 6, 7]

, , , a . += , a - .

+, .

def +(v)
  new_vector = self.class.new
  new_vector.x = @x + v.x
  new_vector.y = @y + v.y
  new_vector
end
+4

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


All Articles