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` ?

···

--
Posted via http://www.ruby-forum.com/\.

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
`object`. Does they reside in the same singleton class? if not where
does `a_method` lives?

Thanks

···

--
Posted via http://www.ruby-forum.com/.

Scopes and look-ups for Ruby constants.

Adam Prescott wrote in post #1101486:

Scopes and look-ups for Ruby constants.

Couldn't understand you. :frowning:

···

--
Posted via http://www.ruby-forum.com/\.

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:

···

On Thu, Mar 14, 2013 at 9:52 PM, Love U Ruby <lists@ruby-forum.com> wrote:

Adam Prescott wrote in post #1101486:
> Scopes and look-ups for Ruby constants.

Couldn't understand you. :frowning:

--
Posted via http://www.ruby-forum.com/\.