是否可以在 Ruby 中创建一元运算符?

Is it possible to create unary operators in Ruby?

我想创建一个运行此方法的一元运算符:

def @*
    self **= 2
end

我有一个项目,其中平方很重要,我不想每次都写'**=2'。我进行了广泛的搜索,但还没有找到答案。任何帮助,将不胜感激。

那不行。 Ruby 支持一元 methods,但仅支持 +-~!.

此外,尽管您可以编写一个计算平方数的方法:

class Numeric
  def square
    self ** 2
  end
end

3.square #=> 9

您不能编写修改数字的方法 – 数字是不可变的。

回答问题:

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

牺牲Integer#~

class Integer
  def ~@
    self ** 2
  end
end

虽然您仍然无法改变 Numeric 实例,但您现在可以在计算中使用它:

5 + ~4
#⇒ 21