"Dennis Misener" <dm / accesscable.net> schrieb im Newsbeitrag
news:MPG.1a46f1de6fb17ed0989681 / library.airnews.net...
> In my efforts to write yet another template language {I know, I
> know ..grin}, I find myself wanting to provide simple named
> parameters ala Mason.  I'd like to insulate the user from the
> mechanics of  "dereferencing" the hashed parameters.
>
> What I desire is an implementation for "parameters" such that:
>
> def announce(args)
> parameters(args,:age=>21)
> "My name is #{first} #{last} and my age is #{age}"
> end
>
> announce(:first=>'John', :last=>'Smith') generates
> "My name is John Smith and my age is 21"
>
> I was thinking something like ....
>
> def parameters(args,defaults)
>     args=defaults.update(args)
>     args.each_pair do |key,value|
> < generate a object with the name 'key' and value 'value'
>   in the scope of the calling routine >
>     end
> end
>
> But the <...> portion has eluded me.  Any assistance would be
> appreciated.

Binding and eval are your friends.  But they do not fully solve your
problem, since local variables are checked syntactically for presence:

def test(hash)
  value = nil
  env = binding

  hash.each do |key,value|
    eval "#{key}=value", env
  end


  puts "last value was #{value}"

  # error because "name" is syntactically checked for presence:
  # puts "name is #{name}"

  hash.each do |key,value|
    eval "printf \"#{key}=%s\n\", #{key}.to_s", env
  end
end

irb(main):219:0*  test( { :foo => "bar", :name => "Smith" } )
last value was Smith
foo=bar
name=Smith

Regards

    robert