Trying to reference a hash using a string value in Ruby
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!
#!/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.
You can eval the string as follows :-
foo = Hash.new
bar = "foo"
eval "#{bar}[\"key\"]=\"value\""
puts foo # {"key"=>"value"}
Remember, eval is evil, but it works:
>> foo = Hash.new
{}
>> bar = "foo"
=> "foo"
>> eval(bar)["key"] = "value"
=> "value"
>> foo
=> {"key"=>"value"}
精彩评论