Inconsistent behavior of singleton methods that access class

N

Nikolai Lugovoi

Sample code (based on fragment from rails/actionpack/test/abstract_unit.rb):

module A
class Sample; end
module Incorrect; end
module Correct; end

class << Sample; def list; @@list ||= []; end; end
class << Incorrect; def list; @@list ||= []; end; end # original pattern
module Correct; def self.list; @@list ||= []; end; end
end

def test_m(obj)
2.times do |i|
l = obj.list
l << "test"
printf "%d) %s %d %s\n", i, obj.name, l.object_id, l.inspect
end
end

[A::Incorrect, A::Correct, A::Sample].each {|mod| test_m(mod) }


Output:

ruby 1.8.7 (2009-09-11 patchlevel 202) [i686-linux]:
0) A::Incorrect -603619398 ["test"]
1) A::Incorrect -603619398 ["test", "test"]
0) A::Correct -603619548 ["test"]
1) A::Correct -603619548 ["test", "test"]
0) A::Sample -603619398 ["test", "test", "test"]
1) A::Sample -603619398 ["test", "test", "test", "test"]


ruby 1.9.2dev (2009-09-28 trunk 25126) [i686-linux]:
0) A::Incorrect 79250400 ["test"]
1) A::Incorrect 79250300 ["test"]
0) A::Correct 79250220 ["test"]
1) A::Correct 79250220 ["test", "test"]
0) A::Sample 79250060 ["test"]
1) A::Sample 79249980 ["test"]

So, the question is, what is the correct way to declare and use such
constructs, and what caused the problem -- bug in ruby or incorrect
use of class variables?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top