Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seejohnrun/4858e232465ab09ae895 to your computer and use it in GitHub Desktop.
Save seejohnrun/4858e232465ab09ae895 to your computer and use it in GitHub Desktop.
tap_try should exist
# Mark NoMethodError(s) coming from a call on `nil`
class NilClass
def method_missing(*)
super
rescue NoMethodError => e
e.instance_variable_set :@real_nil, true
raise e
end
end
class Object
# Implement a tap_try method to avoid "try-chaining"
def tap_try(&block)
yield self
rescue NoMethodError => e
return nil if e.instance_variable_get :@real_nil
raise e
end
end
# Usage
puts 'hello'.tap_try { |s| s.reverse.length }.inspect # 5
puts nil.tap_try { |s| s.reverse.length }.inspect # nil
puts 1.tap_try { |s| s.reverse.length }.inspect # NoMethodError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment