新手问题 ruby 能否自动生成变量名?

hyanwang · 2014年06月26日 · 最后由 hyanwang 回复于 2014年07月11日 · 2471 次阅读

比如我有一个 array = [“a","b","c"] 然后自动分别生成变量名 a,b,c 的 Hash 或是其他的类?

Matz himself weighs in here: https://www.ruby-forum.com/topic/155673#685906

I read from somewhere that now Ruby can't dynamically create local variable. Is it true or just a bug? The local variables are created in compile time, so that local variables that are defined in eval() cannot be accessed outside of eval. In 1.8, irb and tryruby does line by line compilation so that local variables are spilled from eval(), but in 1.9, it's strictly prohibited even under line-by-line compilation.

可以用 Struct 和 OpenStruct

array = ["a","b","c"]
array.each do |value|
  instance_variable_set("@#{value}", "what you want")
end

没看元编程的书?

#4 楼 @mystery 还没有来得及看这本书。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号