Calling Variable in the "fly" *inside loop

Hello there, I’m self though beginner programmer in ruby, and sometimes
I came up with strange ideas that sometimes work and sometimes not.

Today I have something I call “constructing variable in fly”, while
Looping i use this number as construct the name of variable.

say I have var1, var2, var3 = “mouse”,“cat”,“dog”

for i in 1…3
puts var + i.to_s

This doesn’t work, I know it doesn’t work but I was wondering why?

Thanks for your time reading this.

The error is:

 undefined local variable or method `var'

When ruby sees this code:

puts var + i.to_s

It first has to execute the part:

var + i.to_s

And to execute that part, ruby fhas to substitute the values for var and
i.to_s into that line of code. Ruby first tries to figure out what the
value of var is. var can either be the name of a variable or it can be a
method call,

def var
puts ‘hi’



Because ruby cannot find a variable named var, nor a def named var, ruby
has no idea what you mean by var, hence the error message.

Your attempt is a common beginner attempt. When you write a program,
you will NEVER variable names that differ only by a
number–that is what arrays are for. The names of the variables are
var[0], var[1], var[2], etc. instead of var1, var2, var3.

You could use the eval() method to do what you want. eval() takes a
string that looks like code as an argument and then executes the

var1, var2, var3 = “mouse”,“cat”,“dog”

for i in 1…3
eval “puts var#{i}”


However, you should start your studies of computer programming with the
following dictate: NEVER USE EVAL.

7stud, you are one awsome dude, thanks man I learn a lot. I’ll remember
to not to use eval lol.

Ivana Zetticci wrote in post #1149167:

7stud, you are one awsome dude, thanks man I learn a lot. I’ll remember
to not to use eval lol.

I don’t get it: why is that funny?



This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs