Struggle with for loop in Ruby

1

I am having difficulty dynamically displaying the contents of variables. For example:

        minha_var_1 = %{Um texto}  
        minha_var_2 = %{Outro texto}  
        minha_var_3 = %{Mais outro texto} 

But, I tried to display both with:

        for i in(0..2)  
          puts minha_var_"#{i}"  
        end  

How to:

        for i in(0..2)  
          puts "minha_var_#{i}"  
        end 

Unsuccessful.

What would be the right way to display this content dynamically?

    
asked by anonymous 21.11.2014 / 20:17

2 answers

4

If you really want to access multiple variables in a loop, the language allows this. You can use the dangerous eval function, which takes as argument a code in the format of a string and executes it. Thus eval("1+1") results in 2 and eval("system 'shutdown now'") turns off your computer. So 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 to 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 wanting to use such a code. 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
    
21.11.2014 / 21:58
0

Preference solution using arrays:

    #criando o array de strings
    minha_var = [%{Um texto}, %{Outro texto}, %{Mais outro texto}]
    #exibindo o array com laço for
    for i in(0..2)
      puts minha_var[i]
    end

But I did not find a solution without the use of arrays ...

    
21.11.2014 / 20:54