@在Ruby函数名中代表什么

编程入门 行业动态 更新时间:2024-10-24 17:21:06
本文介绍了@在Ruby函数名中代表什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

@ 在以下 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函数名中代表什么

本文发布于:2023-11-25 02:42:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   代表   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!