Alex Rivera | Logout

What does to_proc method mean in Ruby?

Asked 2013-02-14T17:58:42.550
65

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 cheaper in terms of memory). If there is anything else I am missing for symbols, then please tell me. Please explain in a simple way what to_proc means and what it is used for.

Edit
Report

1 Answer

49

The easiest way to explain this is with some examples.

(1..3).collect(&:to_s)  #=> ["1", "2", "3"]

Is the same as:

(1..3).collect {|num| num.to_s}  #=> ["1", "2", "3"]

and

[1,2,3].collect(&:succ)  #=> [2, 3, 4]

Is the same as:

[1,2,3].collect {|num| num.succ}  #=> [2, 3, 4]

to_proc returns a Proc object which responds to the given method by symbol. So in the third case, the array [1,2,3] calls its collect method and. succ is method defined by class Integer. So this parameter is a short hand way of saying collect each element in the array and return its successor and from that create a new array which results in [2,3,4]. The symbol :succ is being converted to a Proc object so it call the Array's succ method.

answered 2013-02-14T18:38:23.560

Your Answer