Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Last active August 29, 2015 14:19
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 yasaichi/6901ffe6afe94b79cfa9 to your computer and use it in GitHub Desktop.
Save yasaichi/6901ffe6afe94b79cfa9 to your computer and use it in GitHub Desktop.
Object#behaves_like?
class Object
def behaves_like?(object)
expected_methods =
if object.respond_to?(:instance_methods)
object.instance_methods
else
object.methods
end
(expected_methods - methods).empty?
end
end
class Foo
def method1; end
end
class Bar
def method1; end
def method2; end
end
foo = Foo.new
bar = Bar.new
p foo.behaves_like?(Bar) # => false
p foo.behaves_like?(bar) # => false
p bar.behaves_like?(Foo) # => true
p bar.behaves_like?(foo) # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment