From: 7stud -- Date: 2009-03-22T12:20:55+09:00 Subject: Re: Passing a named function instead of a code block? James Coglan wrote: > 2009/3/20 7stud -- > >> >> &method(:square1) >> > grab a method as an object without calling it, we need to use >> preceded by some symbol. > Yes, it probably looks that way. To see the difference it helps to know > how > Ruby is parsed. :square1 is an atomic unit representing the symbol whose > name is 'square1'. ":" is not an operator, it is part of the syntax for > symbols. However, "&" is an operator responsible for casting between > procs > and blocks. The expression '&square1' should be read '&( square1 )', > that is > we call square1 and cast the result of that using '&'. The same applies > to > 'method'. 'method' is a method that takes a symbol/string and returns > the > Method object with that name in the current scope. 'method(square1)' > would > be interpreted as a call to square1, passing the result to 'method'. > > So, '&square1' throws an error because you're calling a method with > insufficient arguments. '&:square1' would try to cast a symbol to a > proc, > which if you're using ActiveSupport would return the block { |object| > object.square1 }. > > '&square2' is fine as square2 is just a variable referring to a proc. > Likewise, '&method(:square1)' is fine because method(:square1) is a > Method > object, which can be cast to a block. Thanks for the explanation. You said that (&) casts between block and Procs. But (&) also appears to be casting a Method to a block in this line: puts c.collect(&method(:fib)) (&) can also be used to cast in the reverse direction, e.g. from a block to a Proc: def test(&aProc) aProc.call(10) end test {|x| puts x} --output:-- 10 Can (&) cast a block to a Method? -- Posted via http://www.ruby-forum.com/.