Is undefined variable equal to nil in Ruby?

I got the error as an undefined variable , I know that nil evaluates to false if used as boolean:

 if y puts "Something" end 
+4
source share
3 answers

An undefined variable is not nil.

An undefined instance variable returns nil (again, if it is undefined).

y throws an exception

@y returns nil

+12
source

No, you get an undefined local variable or method error message. But if you want to check if something is defined or not, you can use the defined? method defined? similar to this

 if defined?(my_var) print 'defined' else print 'not defined' end 
+9
source

There is a slight wrinkle. Try the following:

 if 5 == 0 y = 'hi' end puts "hello" if y 

y was "defined" in the if block. Remove this block and this will result in an error.

+2
source

All Articles