Weird Things I Encountered In My Development Journey Explained

Ruby: Variables — Do I exist or not?

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:

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

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

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:

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 .

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.

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store