From: Gregory Brown Date: 2007-07-04T09:19:00+09:00 Subject: Re: Using a block to surround a string? On 7/3/07, Matt Greer wrote: > Is the &block parameter necessary? When is it necessary? You should not use &block and yield together. Use one or the other. &block is necessary when you are passing a block to another method. e.g. def foo(&a) puts "In foo" bar(&a) end def bar puts "In bar" yield end foo { puts "in block" } OUTPUT: In foo In bar in block > 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? Right, block local variables that are defined within the block disappear when the block exits. Blocks can access and modify local variables in the scope the *block* is defined, but not within the method. Here's a set of examples all rolled together for that: def foo a = 1 yield(a) puts "a in method #{a}" end b = 3 puts "b before block: #{b}" foo { |a| b += 2; a += 1; puts "a in block: #{a}" } OUTPUTS: b before block: 3 a in block: 2 a in method 1 b after block: 5 puts "b after block: #{b}"