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
We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
+=
, 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
.plane.x += 5
, the +
message is send to plane.x
, not plane
. So you should override +
method in the class of x
, not Plane
.@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.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
The +=
operator is not associated to any method, it is just syntactic sugar, when you write a += b
the Ruby interpreter transform it to a = a + b
, the same is for a.b += c
that is transformed to a.b = a.b + c
. Thus you just have to define the methods x=
and x
as you need:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With