C:\>ruby -v ruby 2.0.0p0 (2013-02-24) [i386-mingw32] C:\>irb --simple-prompt DL is deprecated, please use Fiddle >> N = 1 => 1 >> obj = Object.new => #<Object:0x2166c00> >> class << obj >> N = 2 >> end => 2 >> def obj.a_method >> puts N >> end => nil >> class << obj >> def another_method >> puts N >> end >> end => nil >> obj.a_method 1 => nil >> obj.another_method 2 => nil >> Both `a_method` and `another_method` are the singleton methods of the object `obj`. Then why gave different output for `N` ?
on 2013-03-13 20:38
on 2013-03-13 20:43
Because def obj.foo uses the top-level value of N = 1, whereas the class << obj; ...; end version uses the value of N previously defined in that scope, and is thus 2. Different scopes.
on 2013-03-13 20:53
both `another_method` and `a_method` are the singleton methods of `obj`. Does they reside in the same singleton class? if not where does `a_method` lives? Thanks
on 2013-03-15 05:52
Adam Prescott wrote in post #1101486:
> Scopes and look-ups for Ruby constants.
Couldn't understand you. :(
on 2013-03-15 17:06
Here is a decent article on the matter: http://jfire.io/blog/2011/01/21/making-sense-of-co... Basically, it seems arbitrary how constant lookup works :(
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.