Last active
August 29, 2015 14:19
-
-
Save yasaichi/6901ffe6afe94b79cfa9 to your computer and use it in GitHub Desktop.
Object#behaves_like?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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