Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Someone else is probably going to mention flip-flops, so let me show you "defined?":

    a = 1
    defined?(a) # => "local-variable"
    defined?(p) # => "method"
    defined?(nothing) # => nil
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



Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: