From: dblack@... Date: 2007-07-04T09:15:59+09:00 Subject: Re: Using a block to surround a string? Hi -- On Wed, 4 Jul 2007, Matt Greer wrote: >> >> So if you *really* wanted to use blocks in your original example, you >> could do: >> >> def around_string(string, &block) >> b, a = yield >> "#{b}#{string}#{a}" >> end >> >> around_string('mystring') { ['before','after'] } >> >> But that is ugly and unidiomatic. :) > > > > Is the &block parameter necessary? When is it necessary? Only if you need to capture the block in an object. > And so I take it with blocks, they are given a new reference to the objects > in question and therefore assigning to the variables in the block has no > effect on the method. ie > > def around_string(string, &block) > b = nil > a = nil > yield(b,a) > "#{b}#{string}#{a}" > end > > around_string('center') { |b, a| b = 'left'; a = 'right' } > > is worthless because in the block I'm merely assigning objects to local > references that go out of scope once the block exits? Method definitions always have their own local scope, so a, b, and string are strictly local to the method. Blocks pick up the scope that they're created in, and can also create variables that weren't already in that scope. Those variables disappear when the block exits; the ones that were there already survive: x = 1 some_method { y = x + 1 } # same x; new y y # undefined; block's y didn't survive x # same x David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)