Ruby 动态变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16419767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby dynamic variable name
提问by Guilherme Carlos
is there any way to create variables in Ruby with dynamic names?
有没有办法在 Ruby 中用动态名称创建变量?
I'm reading a file and when I find a string, generates a hash.
我正在读取一个文件,当我找到一个字符串时,会生成一个哈希值。
e.g.
例如
file = File.new("games.log", "r")
file.lines do |l|
l.split do |p|
if p[1] == "InitGame"
Game_# = Hash.new
end
end
end
How could I change # in Game_# to numbers (Game_1, Game_2, ...)
我如何将 Game_# 中的 # 更改为数字(Game_1、Game_2、...)
回答by sawa
You can do it with instance variables like
你可以用像这样的实例变量来做到这一点
i = 0
file.lines do |l|
l.split do |p|
if p[1] == "InitGame"
instance_variable_set("@Game_#{i += 1}", Hash.new)
end
end
end
but you should use an array as viraptor says. Since you seem to have just a new hash as the value, it can be simply
但是你应该像 viraptor 所说的那样使用一个数组。由于您似乎只有一个新的哈希值,因此可以简单地
i = 0
file.lines do |l|
l.split do |p|
if p[1] == "InitGame"
i += 1
end
end
end
Games = Array.new(i){{}}
Games[0] # => {}
Games[1] # => {}
...
回答by viraptor
Why use separate variables? It seems like you just want Gameto be a list with the values appended to it every time. Then you can reference them with Game[0], Game[1], ...
为什么要使用单独的变量?似乎您只想Game成为一个每次都附加值的列表。然后你可以用Game[0], Game[1], ...
回答by fangxing
If you really want dynamic variable names, may be you can use a Hash, than your can set the key dynamic
如果你真的想要动态变量名,可能你可以使用哈希,而不是你可以设置键动态
file = File.new("games.log", "r")
lines = {}
i = 0
file.lines do |l|
l.split do |p|
if p[1] == "InitGame"
lines[:"Game_#{i}"] = Hash.new
i = i + 1
end
end
end

