I do not know the meaning of @ in:
def -@
Test.new(-@x,-@y)
end
What does @ mean here?
To define unary methods minus, plus, tilde, and not (!), follow the operator with an @ as in +@ or !@. Unary methods accept zero arguments.
Example:
class C
def -@
puts "you inverted this object"
end
end
obj = C.new
-obj # prints "you inverted this object"
This is how unary operator overloading is done in Ruby.
@x and @y are the instance variables of the Test instances. Now suppose you have the value of @x as 5. So -@x is essentially -5, which is just a call to the overloaded unary minus method which is defined by Fixnum class for its instances.
Which @ are you talking about?
The first one is just part of the name of the method, just like b is part of the name of the method in def bar. In particular, this is the method that is called when you use the unary prefix - operator, as in -42.
The other two are sigils indicating instance variables.
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