我如何用单词重命名运算符方法,同时尊重ruby中的sintax?

问题描述 投票:-1回答:3

我正在尝试在使用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 operators rename alias
3个回答
0
投票

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

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

[Trait.new.with x是一个方法调用,等效于Trait.new.send(:with, x),而Trait.new with xTrait.new(with(x)),这不是您想要的。

您的alias创建方法,但不创建运算符。您无法创建全新的运营商。

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


0
投票

您可能在方法调用中错过了.

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

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.