From: Stefan Codrescu Date: 2012-07-25T14:56:06+09:00 Subject: Re: String interpolation / hash of local variables Try this: z = 1 y = 2 hash = Hash.new local_variables.each do |var| hash[var] = eval var end puts h That should give you a hash of the local variables. On Jul 24, 2012, at 9: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. > > -- > Posted via http://www.ruby-forum.com/. >