[Ruby] eval question
Ali Rizvi
aliabbasrizvi at gmail.com
Mon Apr 30 14:23:05 PDT 2007
On 4/30/07, Aaron Patterson <aaron at tenderlovemaking.com> wrote:
>
> My brain may be dead today, so hopefully the community can help. :-(
>
> In this code, 'easy_lover' is defined, but for some reason
> 'phil_collins' is not. First, why is that? Second, can I make it so?
> You can have Easy Lover without Phil!
>
> eval(<<END
> phil_collins = 'awesome'
> def easy_lover
> "She'll get a hold on you believe it"
> end
> END
> )
>
> puts easy_lover
> puts phil_collins # Error!
Just as I suspected you have a scoping problem.
Your variable (phil_collins) is limited in scope within the eval while your
method is in the main/kernel scope which lives on after the eval while
variable seizes to exist beyond that scope.
The following would work:
eval(<<END
phil_collins = 'awesome'
def easy_lover
"She'll get a hold on you believe it"
end
puts phil_collins
END
)
puts easy_lover
Hope this helps.
Ali
> --
> Aaron Patterson
> http://tenderlovemaking.com/
> _______________________________________________
> Ruby at zenspider.com - Seattle.rb non-commercial list
> http://www.zenspider.com/seattle.rb
> http://www.zenspider.com/mailman/listinfo/ruby
>
More information about the Ruby
mailing list