If you really want to access multiple variables in a loop, the language allows it. You can use the dangerous function eval
, which takes as argument a code in the format of a string and executes it. So eval("1+1")
results in 2
and eval("system 'shutdown now'")
shuts down your computer. Therefore you can access your variables using eval("minha_var_1")
or eval("minha_var_2")
. It’s a matter of building the right string and moving on to the eval
.
minha_var_1 = "Um texto"
minha_var_2 = "Outro texto"
minha_var_3 = "Mais outro texto"
for i in 1..3
puts eval("minha_var_#{i}")
end
But, of course, there is no conceivable reason for you to want to use code like this. Use arrays or a hash for this task:
Using Array:
minha_array = ["Um texto", "Outro texto", "Mais outro texto"]
for i in 0..2 # note que arrays contam a partir do zero
puts minha_array[i]
end
Using Hash:
meu_hash = {
1 => "Um texto",
2 => "Outro texto"
3 => "Mais outro texto"
}
for i in 1..3
puts minha_array[i]
end
puts( '--- loop #1 ---' ) for i in ["texto1","texto2","texto3"] do puts( i ) end would be what you want it to be?
– haykou
Thanks for the reply @haykou, but tested and did not work...
– Victoralm
Using array I can do the display, but without using arrays anything...
– Victoralm