From: Sam Duncan Date: 2012-07-26T05:14:05+09:00 Subject: Re: String interpolation / hash of local variables On 07/25/2012 03:08 PM, Gerbeck Shark wrote: > Hello all- > > I'm trying to do something likes > > Demonstration Ruby/logic > > ------- > template =<<-HTML >
%{example}
> ... >
%{foobar}
> HTML > > for i in special_list > example = .... > foobar = ... > arr.push template % return_magical_hash_with_local_variables() > ------- > > in Python there is a locals() function that returns a dictionary/hash of > local variables. > > In Ruby I've found local_variables() but that does not provide the > values. It should for just the example above! Or perhaps I can be > enlightened by someone here? > > The other, dirtier idea is something like this: > > ------- > template = %q{ >
#{example}
> ... >
%{foobar}
> } > > for i in special_list > example = .... > foobar = ... > arr.push eval("\"template\"") > ------- > > I believe one should avoid calling eval as much as possible. I tried the > "Facets" package, > "String.interpolate{template}" calls eval, it just masks the fact. > > This could be avoided if there were a function that return a dictionary > or hash of local variables. > What about simply > irb 1.9.3p125 :001 > template = "
%{example}
\n
%{foobar}
" => "
%{example}
\n
%{foobar}
" 1.9.3p125 :002 > arr = [] => [] 1.9.3p125 :003 > magical_hash_with_local_variables = {} => {} 1.9.3p125 :004 > magical_hash_with_local_variables[:example] = "magical" => "magical" 1.9.3p125 :005 > magical_hash_with_local_variables[:foobar] = "hash" => "hash" 1.9.3p125 :006 > arr.push template % magical_hash_with_local_variables => ["
magical
\n
hash
"] No eval. No external dependencies. In your loop you just populate your magical hash anew. Sam