On 2/20/07, Paul Danese <pdanese / rib-x.com> wrote:
> Hi,
>
>
>
> i'm a roob noob and I'm trying to grasp procs/blocks/etc.
>
>
>
> specifically, I'd like to pass a piece of code into a method.
>
> the piece of code will contain a variable name and an assignment
>
>
>
> e.g.
>
>
>
> ####################
>
> def lamb_test
>
>     cond = 'hello'
>
>     yield
>
>     puts cond + ' ' + name
>
>   end
>
> lamb_test {name = 'bob'}
>
> ###################
>
>
>
> When I do this, I get the following error:
>
> "undefined local variable or method `name' for main:Object...
>
>
>
> is it possible to define a local variable like this on the fly with
> blocks?
>
> obviously, this is an oversimplified case but I want to be able to
> dynamically insert a local variable and an assignment to that variable
> into the "generic" function lamb_test
>
> Is there a better way?
>
>

yield will return the value from the block it executes. Just have your
block return the name 'bob' ...

def lamb_test
  cond = 'hello'
  name = yield
  puts cond + ' ' + name
end

lamb_test { 'bob' }    #=> 'hello bob'

In the more general case, you would need to use one of the 'eval'
methods in order to create a new local variable in a local namespace.
However, (1) the 'eval' methods work only on strings and not blocks,
and (2) they are mostly evil and should be handled with great care.

Blessings,
TwP