如何根据 ruby 中的语法重命名带有单词的运算符方法?

how can i rename a operator method with words, respecting sintax in ruby?

我正在尝试为使用 ruby 中的运算符的 class 方法添加别名。我的问题是我想使用运算符的语法保留新别名

def &(estrategia) 做某事 结束

我希望在 Myclass.new & estrategia 中得到相同的结果,但像这样: Myclass.new 有策略 ruby有没有办法实现这个?

   class Trait
     def & (strategy)
        p "hi #{strategy}"
     end
   alias with &
  end

 Trait.new & "John"
 Trait.new with "John"

您可能错过了 . 方法调用。

class Trait
     def & (strategy)
        p "hi #{strategy}"
     end
   alias with &
end

Trait.new.& "John"
Trait.new.with "John"

Ruby 具有您可以覆盖的特定运算符,例如 %+&,但您不能随心所欲地发明任意运算符。您需要使用已有的。

这是 Ruby 解析器工作方式的函数。它只能识别常规方法调用之外的一组预定义符号。

Trait.new.with x是一个方法调用,相当于Trait.new.send(:with, x),而Trait.new with xTrait.new(with(x)),这不是你想要的。

您的 alias 创建了一个 方法 ,它没有创建一个运算符。您无法创建全新的运算符。

您将不得不在 x & yx.with y 两种形式之间做出决定。

& 是 Ruby 中的默认运算符,您可以使用您的方法覆盖。但是 with 不是运算符。在这种情况下,您需要向 Ruby 添加一个新的运算符,这有点棘手。 这里有关于在 Ruby 中添加新运算符的讨论 Define custom Ruby operator,但我认为这样做不值得。