Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby dynamic variable name

Tags:

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.

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

like image 358
Guilherme Carlos Avatar asked May 07 '13 13:05

Guilherme Carlos


People also ask

How to name a variable in Ruby?

Variable names in Ruby can be created from alphanumeric characters and the underscore _ character. A variable cannot begin with a number. This makes it easier for the interpreter to distinguish a literal number from a variable. Variable names cannot begin with a capital letter.

What is a variable Ruby?

A variable is a name that Ruby associates with a particular object. For example: city = "Toronto" Here Ruby associates the string "Toronto" with the name (variable) city. Think of it as Ruby making two tables. One with objects and another with names for them.

How do you add a variable to a string in Ruby?

Instead of terminating the string and using the + operator, you enclose the variable with the #{} syntax. This syntax tells Ruby to evaluate the expression and inject it into the string.


1 Answers

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] # => {} ... 
like image 123
sawa Avatar answered Sep 23 '22 07:09

sawa