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

hyanwang · June 26, 2014 · Last by hyanwang replied at July 11, 2014 · 2474 hits

比如我有一个 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 还没有来得及看这本书。

You need to Sign in before reply, if you don't have an account, please Sign up first.