Skip to content

Instantly share code, notes, and snippets.

@anibali
Created March 20, 2010 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anibali/338979 to your computer and use it in GitHub Desktop.
Save anibali/338979 to your computer and use it in GitHub Desktop.
This code enables safe navigation via the function '_?'.
# This code enables safe navigation via the function '_?'. Examples of
# usage:
#
# "test"._?.no_such_method # NoMethodError
# " test "._?.strip #=> "test"
# nil._?.strip #=> nil
#
# In summary, `obj._?.some_method` can be thought of as doing
# `obj.nil? ? nil : obj.some_method`
Object.class_eval { def _? ; self ; end }
NilClass.class_eval { def _? ; SafeNilClass.new ; end }
class SafeNilClass
def method_missing(*args, &block)
nil.send(*args, &block) rescue nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment