Inconsistent behavior of singleton methods that access class

Discussion in 'Ruby' started by Nikolai Lugovoi, Sep 27, 2009.

  1. 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?
    Nikolai Lugovoi, Sep 27, 2009
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Proton Projects - Moin

    Singleton - Whether Cloneable overrides Singleton

    Proton Projects - Moin, Mar 26, 2007, in forum: Java
    Replies:
    4
    Views:
    3,214
    Proton Projects - Moin
    Mar 27, 2007
  2. Paul McMahon
    Replies:
    3
    Views:
    195
    David A. Black
    Jun 9, 2008
  3. Kenneth McDonald
    Replies:
    5
    Views:
    297
    Kenneth McDonald
    Sep 26, 2008
  4. Daniel DeLorme
    Replies:
    14
    Views:
    236
    Brian Candler
    Dec 14, 2008
  5. Charles Oliver Nutter

    Singleton methods without the singleton class

    Charles Oliver Nutter, Mar 15, 2010, in forum: Ruby
    Replies:
    4
    Views:
    195
    Charles Oliver Nutter
    Mar 22, 2010
Loading...

Share This Page