What do `def +@` and `def -@` mean?

前端 未结 1 1188
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 23:22

In this Haskell-like comprehensions implementation in Ruby there\'s some code I\'ve never seen in Ruby:

class Array
  def +@
    # implementation
  end

  de         


        
相关标签:
1条回答
  • 2021-01-01 23:41

    They are unary + and - methods. They are called when you write -object or +object. The syntax +x, for example, is replaced with x.+@.

    Consider this:

    class Foo
      def +(other_foo)
        puts 'binary +'
      end
    
      def +@
        puts 'unary +'
      end
    end
    
    f = Foo.new
    g = Foo.new
    
    + f   
    # unary +
    
    f + g 
    # binary +
    
    f + (+ g) 
    # unary +
    # binary +
    

    Another less contrived example:

    class Array
      def -@
        map(&:-@)
      end
    end
    
    - [1, 2, -3]
    # => [-1, -2, 3]
    

    They are mentioned here and there's an article about how to define them here.

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