Symbol#to_proc with custom methods

前端 未结 2 1261
悲哀的现实
悲哀的现实 2021-01-05 21:29

I like how in Ruby you can pass methods as blocks like so using Symbol#to_proc:

[1.0, 2.0, 3.0].map(&:to_i)
#=> [1, 2, 3]
相关标签:
2条回答
  • 2021-01-05 22:04

    You would have to define times_three on Integer or Numeric.

    Symbol to Proc explained by Peter Cooper: https://www.youtube.com/watch?v=aISNtCAZlMg

    0 讨论(0)
  • 2021-01-05 22:07
    class Integer
      def times_three
        return self * 3
      end
    end
    

    Now, because times_three is now a method of the Integer class, you can do symbol to proc...

    [1, 2, 3].map(&:times_three)
    

    If you want to access a method that isn't part of the object's class but acts on an object, you need to pass the object as an argument to the method...

    def times_three(x)
      x * 3
    end
    
    [1, 2, 3].map{|i| times_three(i) }
    

    the symbol to proc needs to use the object as a receiver.

    [1, 2, 3].map(&:some_action)
    

    is equivalent to

    [1, 2, 3].map{|i| i.some_action}
    
    0 讨论(0)
提交回复
热议问题