Difficulty with for loop in Ruby

Asked

Viewed 1,488 times

1

I’m having trouble dynamically displaying the content of variables.
Ex:

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

But I’ve tried to show off so much with:

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

Like:

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

Unsuccessfully.

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

  • puts( '--- loop #1 ---' ) for i in ["texto1","texto2","texto3"] do puts( i ) end would be what you want it to be?

  • Thanks for the reply @haykou, but tested and did not work...

  • Using array I can do the display, but without using arrays anything...

2 answers

4


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

0

Prone solution making use of 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 couldn’t find a solution without using arrays...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.