From: Eric Christopherson Date: 2010-02-22T05:29:34+09:00 Subject: Re: Ruby conditionals subtlety? On Sun, Feb 21, 2010 at 8:33 AM, Brian Candler wrote: > Eric Christopherson wrote: >> I think I understand the gist of this -- if the parser has seen foo >> already, it is considered "defined" -- but how does the distinction of >> method vs. local variable matter in this context? As far as I can >> tell, defined? works the same on local variable names and method >> names. > > irb(main):001:0> bar = 123 > => 123 > irb(main):002:0> defined?(bar) > => "local-variable" > irb(main):003:0> defined?(puts) > => "method" > irb(main):004:0> defined?(baz) > => nil > > furthermore: > > irb(main):005:0> puts = "Hello" > => "Hello" > irb(main):006:0> defined?(puts) > => "local-variable" > > So, defined?(xxx) will return non-nil if xxx is a local variable (a > decision made at parse time), and if not then if the current object has > a method called :xxx (which is only known at run time). Hence > > foo = 123 > bar if defined?(foo) > > is the same as > > foo = 123 > bar if "local-variable" > > because foo is known at parse-time to be a local variable. > > Regards, Ah, thanks -- I wasn't grokking the parse-time/runtime distinction in this case. So: def foo; 456; end unless defined? foo puts foo will print 456, because at parse time foo is undefined, even though it gets made into a method name at runtime.