yzyzsun
yzyzsun

Reputation: 367

Why does Ruby throw NameError here?

When I run the code below:

puts s while (s = gets.chomp) != '42'

Ruby will throw Undefined local variable or method `s' for main:Object (NameError). Why?

Upvotes: 0

Views: 80

Answers (3)

xjlin0
xjlin0

Reputation: 350

If you really want to make a single line you can get s defined first, but it's ugly

while (s = gets.chomp) != '42' ; puts s ; end

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78443

s isn't defined yet, at the puts s statement.

What you're doing is basically equivalent to:

begin
  puts s                           # s is undefined here
end while (s = gets.chomp) != '42'

Put the while block first to make it work:

while (s = gets.chomp) != '42'     # s gets defined here
  puts s
end

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

Ruby is parsed left-to-right, s is used before it is defined.

Initialization order of local variables was changed somewhere around Ruby 1.9, I believe. You should restructure your code or upgrade to a more recent version of Ruby. (Note that 1.8 is no longer maintained.)

Upvotes: 4

Related Questions