chibi03
chibi03

Reputation: 121

Understanding Ruby - undefined local variable

I've been playing around with Ruby and have come across this weird behavior. Could anyone please tell me why this is happening?

if I run:

def my_fn
  if false then
    a = {:a=>10, :b=>20}
  end
  puts a.class
  a || {}
end

and print the result the code compiles successfully and returns {}. But if I change the code to:

def my_fn
  puts a.class
  a || {}
end

it doesn't return {} but throws an Error. "'my_fn': undefined local variable or method 'a' for main:Object (NameError)"

Shouldn't a just be nil and not cause an error?

Upvotes: 2

Views: 76

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

This is because - The local variable is created when the parser encounters the assignment, not when the assignment occurs.

In the first code parser sees the line a = {:a=>10, :b=>20}, so a variable created, but no assignment happened. Thus a is nil. As per the all known facts a || {} returns {}.

In the second code there parser didn't see any assignment happened with a, so a has not been created as a local variable nor you create a method named as a. Thus when you tried to use a, got a valid error as you reported, which is undefined local variable or method 'a'.

Upvotes: 9

Related Questions