Ruby 动态变量名 [英] Ruby dynamic variable name

查看:58
本文介绍了Ruby 动态变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Ruby 中创建具有动态名称的变量?

is there any way to create variables in Ruby with dynamic names?

我正在读取一个文件,当我找到一个字符串时,会生成一个哈希值.

I'm reading a file and when I find a string, generates a hash.

例如

file = File.new("games.log", "r")

file.lines do |l|
  l.split do |p|
    if p[1] == "InitGame"
      Game_# = Hash.new
    end
  end
end

如何将 Game_# 中的 # 更改为数字(Game_1、Game_2、...)

How could I change # in Game_# to numbers (Game_1, Game_2, ...)

推荐答案

你可以用像

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

但是你应该像 viraptor 所说的那样使用数组.由于您似乎只有一个新的哈希值,因此可以简单地

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

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] # => {}
...

这篇关于Ruby 动态变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆