Skip to content

Instantly share code, notes, and snippets.

@Tensho
Created August 27, 2018 20:15
Show Gist options
  • Save Tensho/3fb6243dcbaf15df1dbd83ac59583fb6 to your computer and use it in GitHub Desktop.
Save Tensho/3fb6243dcbaf15df1dbd83ac59583fb6 to your computer and use it in GitHub Desktop.

Revisions

  1. Tensho created this gist Aug 27, 2018.
    28 changes: 28 additions & 0 deletions count_ruby_instances_by_class_1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    class A
    def self.count
    @count
    end

    def self.count=(v)
    @count = v
    end

    def initialize
    self.class.count += 1
    end
    end

    class B < A
    @count = 0
    end

    class C < A
    @count = 0
    end

    B.new
    C.new
    C.new

    B.count #=> 1
    C.count #=> 2
    10 changes: 10 additions & 0 deletions count_ruby_instances_by_class_2.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    A = Class.new
    B = Class.new(A)
    C = Class.new(A)

    B.new
    C.new
    C.new

    ObjectSpace.each_object(B).count #=> 1
    ObjectSpace.each_object(C).count #=> 2