I was expecting the following snippet:
var2 = "Not Empty" unless defined? var2
to return "Not Empty", but I got nil. Any insight into why this is happening?
I was expecting the following snippet:
var2 = "Not Empty" unless defined? var2
to return "Not Empty", but I got nil. Any insight into why this is happening?
defined? method will return:
nil => expression not recognizable
The problem in the above snippet is the scope of the local variable. Its end on the line where you using it. To learn more about local variable, please check this: local_variable
pry(main)> p "local_var is not initialized" unless defined? local_var
=> "loca_var is not initialized"
but if you do this:
pry(main)> local_var = "initialized" unless defined? local_var
=> nil
local_var is still nil because its scoped end after that line, so whatever assigned were wasted.
Solution: I will suggest if you want this behaviour then use this one:
local_var ||= "initialized"
Try var2 = "Not Empty" if var2.nil? if you're trying to figure out if a variable is nil or not. defined? is used much more rarely and for different purposes (see below).
irb(main):009:0> var2 = nil
=> nil
irb(main):010:0> var2 = "Not Empty" if var2.nil?
=> "Not Empty"
irb(main):011:0> var2
=> "Not Empty"
irb(main):012:0> var2 = 'foo'
=> "foo"
irb(main):013:0> var2 = "Not Empty" if var2.nil?
=> nil
irb(main):014:0> var2
=> "foo"
If you aren't sure whether or not a variable has even been declared, you can use the following syntax:
if defined?(var2).nil?
var2 = "Not Empty"
end
(It doesn't work all on one line for some strange reason, as @Jordan has pointed out, but this works.)
However, the idiomatic Ruby way to do this, in general, is called a "nil guard" and looks like the following:
var2 ||= "Not Empty"