@ 在以下 Ruby 代码中代表什么:
What does @ stand for in the following Ruby code:
module TestRocket extend Module.new { attr_accessor :out } def _test(a, b); send((call rescue()) ? a : b); end def +@; _show _test :_pass, :_fail end def -@; _show _test :_fail, :_pass end def ~@; _show _pend; end def !@; _show _desc; end def _show(r); (TestRocket.out || $>) << r; r end def _pass; " OK\n"; end def _fail; " FAIL @ #{source_location * ':'}\n"; end def _pend; "PENDING '#{call}' @ #{source_location * ':'}\n"; end def _desc; " FIRE '#{call}'!\n"; end end Proc.send :include, TestRocket然后用作:
+-> { Die.new(2) } --> { raise } +-> { 2 + 2 == 4 }函数名中@怎么变成'->'?
How does @ turn into '->' in the function name?
推荐答案四个一元运算符的方法名称 +, -, ~ 和 ! 分别是 +@、-@、~@ 和 !@.所以看起来很有趣的方法定义:
The method names for the four unary operators +, -, ~, and ! are +@, -@, ~@, and !@. So the funny looking method definitions:
def +@; _show _test :_pass, :_fail end def -@; _show _test :_fail, :_pass end def ~@; _show _pend; end def !@; _show _desc; end只需为这四个一元运算符定义重载.然后使用 Proc.send :include, TestRocket 将 TestRocket 修补到 Proc 类中.
just define overloads for those four unary operators. Then TestRocket is patched into the Proc class using Proc.send :include, TestRocket.
这个:
-> { Die.new(2) }只是一个 lambda 定义和另一种编写 lambda { Die.new(2) } 的方式.然后,将 TestRocket 修补到 Proc 中,我们可以这样说:
is simply a lambda definition and another way of writing lambda { Die.new(2) }. Then, with TestRocket patched into Proc we can say this:
+-> { Die.new(2) } # + lambda { Die.new(2) }它会运行这个方法:
def +@; _show _test :_pass, :_fail end作为该 lambda 的实例方法.
as an instance method on that lambda.
看起来有点滥用一元运算符重载来发明"一些看起来像 new -->, ~->, ... 运营商.
Looks like a bit of an abuse of the unary operator overloading to "invent" something that looks like new -->, ~->, ... operators.
更多推荐
@在Ruby函数名中代表什么
发布评论