Singleton method

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 ?

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.

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

Scopes and look-ups for Ruby constants.

Adam P. wrote in post #1101486:

Scopes and look-ups for Ruby constants.

Couldn’t understand you. :frowning:

Here is a decent article on the matter:
http://jfire.io/blog/2011/01/21/making-sense-of-constant-lookup-in-ruby/

Basically, it seems arbitrary how constant lookup works :frowning:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs