2012-04-04 3 views
0
module MyModule 
    def self.my_method 
     @instance_variable ||= "some string" 
    end 
end 

MyModuleを含む別のモジュールOtherModuleを考えてみましょう。 OtherModuleのコードでmy_methodを複数回呼び出すと、@instance_variableは複数回インスタンス化されますか?それとも一度ですか?モジュール

答えて

1

更新答え:デリゲートモジュールは、メソッドを呼び出す場合

  1. 、エラーが発生します。
  2. 元のモジュールがメソッドを呼び出す場合、クラスインスタンス変数は1回だけインスタンス化されます。
  3. モジュールで「クラスメソッド」を定義する場合は、self.xxを定義して、単純に拡張/インクルードすることはできません。それを「拡張する」か「固有クラスに含める」のいずれかにする必要があります。

    module SomeModule 
        def self.aim_to_be_class_method ; end; 
        def aim_to_be_instance_method ; end; 
    end 
    
    # class methods: [] 
    # instance methods: ["aim_to_be_instance_method"] 
    class SomeClassIncludingTheModule 
        include SomeModule 
    end 
    
    # class methods: ["aim_to_be_instance_method"] 
    # instance methods: [] 
    class SomeClassExtendingTheModule 
        extend SomeModule 
    end 
    
    # class methods: ["aim_to_be_instance_method"] 
    # instance methods: [] 
    class SomeClassMadeEigenClassIncludingModule 
        class << self 
        include SomeModule 
        end 
    end 
    

あなたのコードは、 "クラスのインスタンス変数" の一例です。書籍< <メタプログラミングruby >>の127ページによれば、「クラスインスタンス変数」はJavaの静的フィールドとみなすことができます。だから、私は大部分の場合、それは一度実行する必要がありますと思います。

詳細については、ユニットテストを書いて何が起こるかをご覧ください。私は自分のユニットテストコードを書いて短い時間のうちに私の答えを更新します。

更新:私のユニットテストと結果:

# all of the code is placed in a file: class_instance_variable_test.rb 

# define a class so that we see its initialize process 
class Apple 
    def initialize 
    puts "Apple initialized~" 
    end 
end 

# define an original_module that calls Apple.new 
module OriginalModule 
    def self.original_method 
    @var ||= Apple.new 
    end 
end 

# define another module to call the original_module 
module DelegateModule 
    include OriginalModule 
end 

# now the test begins 
require 'test/unit' 
class ClassInstanceTest < Test::Unit::TestCase 

    # output of this test case: 
    # NoMethodError: undefined method `original_method' for DelegateModule:Module  
    def test_if_delegate_module_could_call_original_method_by_including_original_module 
    DelegateModule.original_method 
    end 

    # output of this test case: 
    # ----- calling from original_method, 3 times called, how many times initialized? 
    # Apple initialized~ 
    # ------ ends 
    def test_if_we_could_call_original_method_from_original_module 
    puts "----- calling from original_method, 3 times called, how many times initialized? " 
    OriginalModule.original_method 
    OriginalModule.original_method 
    OriginalModule.original_method 
    puts "------ ends " 
    end 

end 
関連する問題