Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Last active Aug 29, 2015
Embed
What would you like to do?
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