From: "David A. Black" Date: 2007-11-01T07:15:01+09:00 Subject: Re: .each do |foo, bar| what does bar do? Hi -- On Thu, 1 Nov 2007, 7stud -- wrote: >> David A. Black wrote: >>>>> That suffers the same problem as David Black's example. >>>> >>>> What problem did mine suffer from? >>>> >>> >>> It doesn't return an array. >> >> Was it supposed to? >> > > Hash#each returns an array(as my examples showed). You said: > >> If you were going to write Hash#each in Ruby, without recourse to >> #each, > > So, yes...your example would have to return an array to implement > Hash#each. Actually Hash#each returns its receiver, which is a hash. I think my code also returned self. > >> If you do this: >> >> some_method(some_proc_object) >> >> you're just passing the Proc object around the same way you would pass >> a string or an array or any other object. >> >> If you do this: >> >> some_method &some_proc_object >> >> you're telling some_method that you want some_proc_object to play the >> special role of code-block. >> > > Ah. So, it's like the splat operator(*)? With the splat operator you > might write: > > def meth1(*args) #gathers the args into an array > meth2(*args) #applied a second time -- explodes the array > end > > def meth2(a, b) > p a > p b > end > > meth1(1, 2) > > So, applying & a second time conceptually converts the Proc object back > to a block and passes it to the method? Yes. I wouldn't bother comparing it to the *. It's a way to use a Proc object as a block. It doesn't have to be the one that was passed in originally: def some_method p = Proc.new {|x| x * 10 } return [1,2,3].map(&p) end >> There could even be a situation where you would do: >> >> some_method(proc_1, proc_2) &proc_3 >> >> i.e., send two procs as regular arguments, and use a third one as the >> code block. >> > > Whoa. That doesn't seem consistent with your earlier example. Why is > proc3 outside the parentheses? It doesn't seem to work: Whoops, that was supposed to be inside, as your tests showed. David -- Upcoming training by David A. Black/Ruby Power and Light, LLC: * Advancing With Rails, Edison, NJ, November 6-9 * Advancing With Rails, Berlin, Germany, November 19-22 * Intro to Rails, London, UK, December 3-6 (by Skills Matter) See http://www.rubypal.com for details!