What does to_proc method mean?

后端 未结 4 585
孤独总比滥情好
孤独总比滥情好 2020-11-28 23:31

I am learning rails and following this thread. I am stuck with the to_proc method. I consider symbols only as alternatives to strings (they are like strings but

4条回答
  •  温柔的废话
    2020-11-28 23:46

    For anybody still a bit stumped, running the following code might make things a little clearer:

    class Symbol
      def to_proc
        proc do |obj|
          puts "Symbol proc: #{obj}.send(:#{self})"
          obj.send(self)
        end
      end
    end
    
    class Array
      def map(&block)
        copy = self.class.new
        self.each do |index|
          puts "Array.map:   copy << block.call(#{index})"
          copy << block.call(index)
        end
        copy
      end
    end
    
    remapped_array = [0, 1, 2].map &:to_s
    puts "remapped array: #{remapped_array.inspect}"
    

    These are not the actual implementations of Symbol.to_proc or Array.map, they are just simplified versions which I'm using to demonstrate how map &:to_s and similar calls work.

提交回复
热议问题