Last active
December 11, 2015 21:29
-
-
Save apotonick/4662983 to your computer and use it in GitHub Desktop.
The problem here is the instance_exec in the anonymous module - the #a method is not mixed into obj.
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
blk = lambda { def a; end } | |
mod = Module.new { instance_exec &blk } # this should add #a to mod. | |
obj = Object.new | |
obj.extend(mod) | |
obj.a #=> undefined method `a' for #<Object:0x970543c> |
@apotonick, I dunno if this is still is relevant but instance_exec is going to add a as a module function to mod. So it can be called using mod.a
If a was to be included to obj via mod, it would need to exist in mod as a instance method, which ironically means one has to add it via class_exec (mo module_exec).
instance_exec (and eval) define class methods when the context is a module/class
class_exec/module_exec (and eval counter parts) define instance methods
Bloody confusing I know. (See http://ilikestuffblog.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/ for a better explanation)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @godfat! It should read