Joe Morano
Joe Morano

Reputation: 1885

Is it possible to insert one variable's value into the name of another variable?

Let's say I have a loop repeating 1000 times.

Previous to the loop, I set 1000 variables, like so:

@n1 = "blabla"
@n2 = "blabla"
@n3 = "blabla"
@n4 = "blabla"
...

I also have a variable @count that counts which iteration the loop is on, ie. it starts at 1 and increases by 1 with each loop. What I want to do is print @n1 if @count = 1, print @n2 if @count = 2, and so forth. In other words, I want ruby to use the value of @count to decide which @n_ variable to use. I don't want to use conditional statements, because I'd need 1000 of them.

Something like this:

@count = 1
if @count < 1001
  puts @("n + @count")
  @count = @count + 1
end

Is there a way to do this?

Upvotes: 0

Views: 114

Answers (3)

spickermann
spickermann

Reputation: 106882

While you can use something like instance_variable_get, you would usually use an array or an hash to store your strings:

n = ["blabla", "blabla", "blabla", ... ]

count = 0
if count < 1000
  puts n[count]
  count += 1
end

Upvotes: 1

fabriciofreitag
fabriciofreitag

Reputation: 2883

Let's say you have an instance called foo, with a thousand instance variables, to loop through them all you could do:

foo.instance_variables.each do |v| 
  p foo.instance_variable_get(v) 
end

That said, you can also use the string name to fetch them:

1000.times do |count|
  p foo.instance_variable_get("@n#{count}") 
end

Upvotes: 2

Felix Livni
Felix Livni

Reputation: 1244

Yes, you can do do this:

if @count < 1001
  instance_variable_set("@#{@count}", @count + 1)
end

It would be more idiomatic to store in a hash, e.g.

h = {}
if @count < 1001
  h[@count] = @count + 1
end

Upvotes: 1

Related Questions