尝试使用 Ruby 中的字符串值引用哈希
我如何使用字符串的值来引用哈希 - 即
#!/usr/bin/env ruby
foo = Hash.new
bar = "foo"
"#{bar}"["key"] = "value"
结果
foo:5:in `[]=': string not matched (IndexError)
from foo:5
如何使用 bar (foo) 的值来引用名为 foo 的哈希?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在此上下文中,
eval(bar)
也可以工作,instance_eval 尝试执行(作为 ruby 代码)您在当前上下文中第一个参数给出的字符串。
在您的示例中,Ruby 尝试调用 String#[]= 方法。你不希望这样:)
希望有帮助。
At this context
eval(bar)
also worksinstance_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 :-
请记住,eval 是邪恶的,但它确实有效:
Remember, eval is evil, but it works: