我正在尝试在使用ruby的运算符的类方法中添加别名。我的问题是我想使用运算符的sintax保留新的别名
def&(strategy)做某事结束
我希望在执行Myclass.new和estrategia时得到相同的结果,但是像这样:Myclass.new与战略红宝石有办法实现这一目标吗?
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 x
是Trait.new(with(x))
,这不是您想要的。
您的alias
创建方法,但不创建运算符。您无法创建全新的运营商。
您将不得不在x & y
与x.with y
这两种形式之间做出选择。
您可能在方法调用中错过了.
。
class Trait
def & (strategy)
p "hi #{strategy}"
end
alias with &
end
Trait.new.& "John"
Trait.new.with "John"
&
是Ruby中的默认运算符,您可以使用方法覆盖。但是with
不是运算符。在这种情况下,您将需要向Ruby添加一个新的运算符,这有点棘手。这里有关于在Ruby中添加新运算符的讨论Define custom Ruby operator,但我认为这样做不值得。