Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

operator overloading - Ruby method for +=

Is there a way to make Ruby able 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. You cannot override compound assignment operators in Ruby. The assignments are handled internally. Instead of +=, you should override +. plane.a += b is the same as plane.a = plane.a + b or plane.a=(plane.a.+(b)). Thus you should also override a= in Plane.
  2. When you write plane.x += 5, the + message is send to plane.x, not plane. So you should override + method in the class of x, not Plane.
  3. When you refer to @variable, you should pay attention to what the current self is. In class Plane; @variable; end, @variable refers to the instance variable of the class. That's different with the one in class Plane; def initialize; @variable; end; end, which is instance variable of the class's instances. So you can put the initialization part into initialize method.
  4. Operator overriding should be treated carefully. Sometimes it is productive and expressive, but sometimes it isn't. Here I think it's better to define a method (e.g. fly) for plane rather than using some 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...