33

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

3
  • Where do the numbers come from? Commented May 7, 2013 at 13:04
  • A variable name with a capital letter is considered bad practice in Ruby unless you are declaring a class or module name. Consider changing Game_ to game_. Commented May 7, 2013 at 13:05
  • 1
    What would you do with those dynamically-created names? Your source code couldn't refer to them except via clunky sends. Looks like an array to me. Commented May 7, 2013 at 13:18

3 Answers 3

46

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] # => {}
...
Sign up to request clarification or add additional context in comments.

1 Comment

9

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.