From: "Eric I." Date: 2008-05-23T07:10:03+09:00 Subject: Re: Why does returning from a block cause a LocalJumpError On May 22, 12:57 am, cbare wrote: > I'm hoping someone can set me straight about something. Take the > following lines of Ruby and output from the interpreter: > > [1,2,3].map {|a| a*a} > > >> [1,4,9] > > [4,5,6].map {|a| return a*a} > > >> LocalJumpError: unexpected return A return within a block returns from the scope that the block is within. So if you had: def some_method [4,5,6].map {|a| return a*a } end Calling some_method would return 16. > I'm trying to fit Ruby's code blocks in with the concept of anonymous > functions that's in my brain from languages like Scheme. It seems that > a code block must be something a little different, because returning > from an anonymous function should be a fine thing to do. It is a bit different. You should look into the Proc class. And even then, the behavior differs as to how you create the Proc instance. Procs created with Proc.new act like blocks. But Procs created with either Kernel.proc or Kernel.lambda work like what you're expecting. > Does a code > block not create an environment for local variables on the stack? Yes, but so do conditionals and loops. And with conditionals and loops you would expect an embedded return not to take you out of the conditional or loop but out of the method that "surrounds" them. And blocks work work that way too. I hope that's helpful. Eric ==== LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE workshops. Ruby Fundamentals Wkshp June 16-18 Ann Arbor, Mich. Ready for Rails Ruby Wkshp June 23-24 Ann Arbor, Mich. Ruby on Rails Wkshp June 25-27 Ann Arbor, Mich. Ruby Plus Rails Combo Wkshp June 23-27 Ann Arbor, Mich Please visit http://LearnRuby.com for all the details.