2

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?

1 Answer 1

9

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'.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, thanks. Do you know any advantages of using this approach? It doesn't seem very intuitive to me.
@chibi03 I linked the documentation also, please go through that, plenty of knowledge there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.