What does to_proc method mean?

后端 未结 4 581
孤独总比滥情好
孤独总比滥情好 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:42

    For me the clearest explanation is seeing a simple implementation of it. Here's what it might look like if I were reimplementing Symbol#to_proc:

    class Symbol  # reopen Symbol class to reimplement to_proc method
      def to_proc
        ->(object) { object.send(self) }
      end
    end
    
    my_lambda = :to_s.to_proc
    
    puts my_lambda.(1)  # prints '1'; .() does the same thing as .call()
    puts my_lambda.(1).class  # prints 'String'
    
    puts [4,5,6].map(&:to_s)  # prints "4\n5\n6\n"
    puts [4,5,6].map(&:to_s).first.class  # prints 'String'
    

提交回复
热议问题