Last active
August 29, 2015 13:57
-
-
Save calleluks/9422602 to your computer and use it in GitHub Desktop.
respond_to_missing? and BasicObject
This file contains hidden or 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 A | |
| def initialize(obj) | |
| @obj = obj | |
| end | |
| def method_missing(message, *args, &block) | |
| @obj.send(message, *args, &block) | |
| end | |
| end | |
| class B < BasicObject | |
| def initialize(obj) | |
| @obj = obj | |
| end | |
| def method_missing(message, *args, &block) | |
| @obj.send(message, *args, &block) | |
| end | |
| end | |
| a = A.new("string") | |
| a.upcase #=> "STRING" | |
| a.respond_to?(:upcase) #=> false | |
| # a.method(:upcase) # Raises NameError if we don't define respond_to_missing? | |
| b = B.new("string") | |
| b.upcase #=> "STRING" | |
| b.respond_to?(:upcase) #=> true | |
| b.method(:upcase) #=> #<Method: String#upcase> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment