views:

40

answers:

3

How would I refer to a hash using the value of a string - i.e.

#!/usr/bin/env ruby
foo = Hash.new
bar = "foo"
"#{bar}"["key"] = "value"

results in

 foo:5:in `[]=': string not matched (IndexError)
 from foo:5

How do I use the value of bar (foo) to reference the hash named foo? Thanks!

+2  A: 
#!/usr/bin/env ruby
foo = Hash.new
bar = "foo"
instance_eval(bar)["key"]="value"

At this context eval(bar) also works

instance_eval tries to execute(as ruby code) the string that you give at first argument in the current context.

In your example, Ruby is trying to invoke the String#[]= method. And you don't want that :)

Hope that helps.

pablorc
+1 That's nice and saves some messing around escaping strings
Steve Weet
Agreed - this is a very clean solution. Thanks for the help!
Jim
A: 

You can eval the string as follows :-

foo = Hash.new
bar = "foo"
eval "#{bar}[\"key\"]=\"value\""
puts foo   # {"key"=>"value"}
Steve Weet
A: 

Remember, eval is evil, but it works:

>> foo = Hash.new
{}
>> bar = "foo"
=> "foo"
>> eval(bar)["key"] = "value"
=> "value"
>> foo
=> {"key"=>"value"}
The MYYN