Weird Things I Encountered In My Development Journey Explained

Ruby: Variables — Do I exist or not?

Shan Shaji
2 min readJun 10, 2021

I am happy with Ruby’s flexibility and duck type-ness. I don't have to explicitly say what I want to do when creating objects. I can create whatever I want on the go, like this:

i_exist = "Hey I am a variable"
i_exist = 2

But what if I try to call something which doesn't exist?

i_dont_exist
=> in `<main>': undefined local variable or method `i_dont_exist' for main:Object (NameError)

It throws an error because the variable does not exist, which does make sense. So what if it was a non-existing instance variable:

@i_dont_exist_either
=> nil

ooh!! I never expected discrimination to exist in Ruby. All instance variables are automatically initialized to nil.

Well, that’s not hard to remember — instance variables are automatically initialized to nil, and variables are not, which throws an error.

So what if there is an impossible situation for a variable to exist like this:

if false
i_am_not_supposed_to_exist = 1
end

I thought calling i_am_not_supposed_to_exist outside the scope might throw an undefined local variable or method error, since that part of the code never gets to run. But to my surprise, it returned nil .

i_am_not_supposed_to_exist
=> nil

The assignment to the i_am_not_supposed_to_exist isn’t executed, but the variable i_am_not_supposed_to_exist is created with a nil value. The parser doesn’t care whether i_am_not_supposed_to_exist is ever assigned a value. Its job is just to scour the code for local variables for which space needs to be allocated.

This was sitting in my drafts for a very long time, I didn’t publish it before because I thought there is not much worth sharing. Hope you like it.

--

--

Shan Shaji

End to End Product Developer with an immense passion for Rails and React. https://github.com/shanshaji