Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @- mean in the following method? [duplicate]

Tags:

ruby

I do not know the meaning of @ in:

def -@
  Test.new(-@x,-@y)
end

What does @ mean here?

like image 602
Adam Lee Avatar asked Feb 10 '23 21:02

Adam Lee


2 Answers

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.

like image 164
Arup Rakshit Avatar answered Mar 04 '23 13:03

Arup Rakshit


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.

like image 35
Jörg W Mittag Avatar answered Mar 04 '23 13:03

Jörg W Mittag