Jechol Lee
Jechol Lee

Reputation: 145

Local variable undefined when it is set in same line

I wrote a simple echo loop, but it gives undefined local variable error.

> puts line while line = gets
NameError: undefined local variable or method `line' for main:Object

Why is line not visible to puts?

I know adding line = nil fixes this error. But I want to know why so.

> line = nil
> puts line while line = gets #==> Works!
apple banana
apple banana

Upvotes: 1

Views: 63

Answers (2)

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

You encounter an error, because Ruby parser reads from top to bottom, left to right, so it reads puts line, but doesn't know anything about this variable.

Your code will work if you rewrite it like this:

while line = gets
  puts line 
end

In this way parser will see assignment first and won't complain.

Upvotes: 4

0aslam0
0aslam0

Reputation: 1961

When you give puts "hello", you give information to the interpreter about what to print.

When you give puts line, interpreter will look for an object line.Otherwise you get the error : NameError: undefined local variable or method 'line' for main:Object. That is the power of declaration! Learn to read error messages. All the best!

Upvotes: 0

Related Questions