what does @ stand for in a Ruby function name

前端 未结 1 1661
半阙折子戏
半阙折子戏 2020-12-05 11:21

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 :         


        
相关标签:
1条回答
  • 2020-12-05 11:40

    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
    

    just define overloads for those four unary operators. Then TestRocket is patched into the Proc class using Proc.send :include, TestRocket.

    This:

    -> { Die.new(2) }
    

    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) }
    

    and it will run this method:

    def +@; _show _test :_pass, :_fail end
    

    as an instance method on that lambda.

    Looks like a bit of an abuse of the unary operator overloading to "invent" something that looks like new -->, ~->, ... operators.

    0 讨论(0)
提交回复
热议问题