what happened when pass a method to iterator method

后端 未结 1 709
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 04:37

As we know, wo can pass a method to a iterator method by a &: prefix.
For example:

[\"a\", \"b\"].map(&:upcase) #=> [\"A\", \"B         


        
相关标签:
1条回答
  • 2021-01-14 05:13

    Here's what works. Explanation below.

    class String
      def rettwo
        self + self
      end
    end
    
    def a_simple_method &proc
      proc.call('a')
    end
    
    def a_iterator_method
      yield 'b'
    end
    
    a_simple_method(&:rettwo) # => "aa"
    a_iterator_method(&:rettwo) # => "bb"
    

    The &: construct is called Symbol#to_proc. It turns symbol into a proc. This proc expects a receiver as a first argument. The remaining arguments are used to call the proc. You're not passing any arguments, hence the "receiver not given" error.

    Here's a demonstration of additional arguments:

    class String
      def say name
        "#{self} #{name}"
      end
    end
    
    def a_simple_method &proc
      proc.call('hello', 'ruby')
    end
    
    
    a_simple_method(&:say) # => "hello ruby"
    

    Here's a definition of Symbol#to_proc from some blog post from 2008. Modern Symbol#to_proc seems to be implemented in C, but this can still help the understanding.

    class Symbol
      def to_proc
        Proc.new { |*args| args.shift.__send__(self, *args) }
      end
    end
    
    0 讨论(0)
提交回复
热议问题