7stud2
(7stud --)
13 March 2013 19:38
1
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.
7stud2
(7stud --)
13 March 2013 19:53
3
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.
7stud2
(7stud --)
15 March 2013 04:52
5
Adam Prescott wrote in post #1101486:
Scopes and look-ups for Ruby constants.
Couldn't understand you.
···
--
Posted via http://www.ruby-forum.com/\ .
Doug1
(Doug)
15 March 2013 16:00
6
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
···
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.
--
Posted via http://www.ruby-forum.com/\ .