Ruby dynamic variable name

后端 未结 3 1835
执念已碎
执念已碎 2020-12-05 10:06

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.

e.g.

file =          


        
相关标签:
3条回答
  • 2020-12-05 10:35

    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
    
    0 讨论(0)
  • 2020-12-05 10:49

    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

    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] # => {}
    ...
    
    0 讨论(0)
  • 2020-12-05 10:56

    Why use separate variables? It seems like you just want Game to be a list with the values appended to it every time. Then you can reference them with Game[0], Game[1], ...

    0 讨论(0)
提交回复
热议问题