defined? is a syntax-construct (not a method) which tries to tell
you if its "parameter" is defined. The rules for this are rather
interesting.
class String
def print
p self
self
end
end
Okay, String#print is just a helper method to prove my point.
defined?("hello".print) # => "method"
defined?("hello".print.strip) # => prints out "hello", then returns "method"
defined?("hello".print.stripp) # => prints out "hello", then returns nil
Okay, so defined? may actually call methods for you to figure out if
it's "defined" or not. What if we try something more complex:
defined?(if true then "hello".print.strip end) # => "expression"
Wait, what? This does not call the print method. In fact, this check
is done entirely at parse-time. "defined?(if true then … end)" will
always return "expression". In fact, anything more complex than local
variables, method calls or constant names will just return "expression".
Well, except for "defined?" though; defined? can't check itself - it's a
syntax error.
Another intresting "feature": If any exception is raised, the whole
expression is considered undefined:
class String; def print; raise; end; end
defined?("hello".print.strip) # => nil
Another intresting "feature": If any exception is raised, the whole expression is considered undefined: