Marcello Barnaba
2/20/2007 6:54:00 PM
Hi,
On Tuesday 20 February 2007 19:33, Paul Danese wrote:
> ####################
> def lamb_test
> cond = 'hello'
> yield
> puts cond + ' ' + name
> end
>
> lamb_test {name = 'bob'}
>
> ###################
the local variables defined in the block live only in the block's scope. if a
local variable is defined out of the block, a closure is made and you can
access (and redefine) that variable in the block:
>> a = 1
=> 1
>> p = proc { a = 2; b = 3 }
=> #<Proc:0xb7ae7150@(irb):8>
>> p.call
=> 2
>> a
=> 2
>> b
=> NameError: ...
> Is there a better way?
well
def lamb_test
cond = 'hello'
name = yield
puts cond + ' ' + name
end
better:
def lamb_test
cond = hello
puts cond + ' ' + yield
end
better:
def lamb_test
puts ['hello', yield].join(' ')
end
even better:
def lamb_test
['hello', yield].join(' ')
end
puts lamb_test { 'world' }
if "puts" is not strictly necessary in your method, take it out, and just
return a string. this way, when you need to print that string on something
different than a text terminal, you don't need to mess with the class you've
written earlier.
HTH! :)
--
pub 1024D/8D2787EF 723C 7CA3 3C19 2ACE 6E20 9CC1 9956 EB3C 8D27 87EF