Ruby method for + =

Is there a way to get Ruby to do something like this?

class Plane @moved = 0 @x = 0 def x+=(v) # this is error @x += v @moved += 1 end def to_s "moved #{@moved} times, current x is #{@x}" end end plane = Plane.new plane.x += 5 plane.x += 10 puts plane.to_s # moved 2 times, current x is 15 
+4
source share
2 answers

The += operator += not associated with any of the methods, it is just syntactic sugar, when you write a += b the Ruby interpreter will convert it to a = a + b , the same for ab += c , which will be converted to ab = ab + c . So you just need to define the methods x= and x as needed:

 class Plane def initialize @moved = 0 @x = 0 end attr_reader :x def x=(x) @x = x @moved += 1 end def to_s "moved #{@moved} times, current x is #{@x}" end end plane = Plane.new plane.x += 5 plane.x += 10 puts plane.to_s # => moved 2 times, current x is 15 
+5
source
  • You cannot override compound assignment operators in Ruby. Appointments are processed internally. Instead of += you should override + . plane.a += b same as plane.a = plane.a + b or plane.a=(plane.a.+(b)) . So you should also override a= in Plane .
  • When you write plane.x += 5 , the + message is sent to plane.x , not Plane . Therefore, you must override the + method in the class x , not Plane .
  • When you refer to @variable , you should pay attention to what the current self . In class Plane; @variable; end class Plane; @variable; end class Plane; @variable; end , @variable refers to an instance variable of a class . This is different from that in class Plane; def initialize; @variable; end; end class Plane; def initialize; @variable; end; end class Plane; def initialize; @variable; end; end , which is an instance variable of class instances . That way you can put the initialization part in the initialize method.
  • Cancellation of the operator must be carefully processed. Sometimes it is productive and expressive, but sometimes it is not. Here I believe that it is better to define a method (for example, fly ) for a plane, and not use any operator.
 class Plane def initialize @x = 0 @moved = 0 end def fly(v) @x += v @moved += 1 end def to_s "moved #{@moved} times, current x is #{@x}" end end plane = Plane.new plane.fly(5) plane.fly(10) puts plane.to_s 
+6
source

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


All Articles