Guilherme
Guilherme

Reputation: 1103

Ruby dynamic variable name

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 = 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, ...)

Upvotes: 33

Views: 32130

Answers (3)

Fangxing
Fangxing

Reputation: 6125

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

Upvotes: 1

sawa
sawa

Reputation: 168101

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

Upvotes: 46

viraptor
viraptor

Reputation: 34145

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], ...

Upvotes: 9

Related Questions