Sealestr
Sealestr

Reputation: 53

Is it possible to create unary operators in Ruby?

I want to create a unary operator that runs this method:

def @*
    self **= 2
end

I have a project where squaring is important, and I don't want to write '**=2' every single time. I have searched extensively, and yet have not found an answer. Any help would be appreciated.

Upvotes: 0

Views: 136

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Answering the question stated:

I have a project where squaring is important, and I don't want to write **=2 every single time.

Sacrifice Integer#~:

class Integer
  def ~@
    self ** 2
  end
end

While you are still unable to mutate the Numeric instance, you are now able to use it in calculations:

5 + ~4
#⇒ 21

Upvotes: 0

Stefan
Stefan

Reputation: 114178

That won't work. Ruby supports unary methods, but only +, -, ~ and !.

Besides, although you can write a method that will square a number:

class Numeric
  def square
    self ** 2
  end
end

3.square #=> 9

you can't write a method that will modify a number – numbers are immutable.

Upvotes: 2

Related Questions