1

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!

3 Answers 3

4
#!/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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

You can eval the string as follows :-

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

Comments

1

Remember, eval is evil, but it works:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.