2016-10-23 14 views
1

extendインスタンスを作成するときと同じ方法でインスタンスを作成するときに、いくつかのインスタンス変数を設定するには、initializeを使用します。この例ではRuby:拡張インスタンス変数

変数セットの拡張「失われた」である。

module Mod 
    def self.extended(base) 
    @from_module = "Hello from Mod" 
    puts "Setting variable to: #{@from_module}" 
    end 

    def hello_from_module 
    return @from_module 
    end 
end 

class Klass 
    def initialize 
    @from_class = "Hello from Klass" 
    end 

    def hello_from_class 
    return @from_class 
    end 
end 

klass = Klass.new  #=> #<Klass:0x00000000ed8618 @from_class="Hello from Klass"> 
klass.extend(Mod)  #=> #<Klass:0x00000000ed8618 @from_class="Hello from Klass"> 
"Setting variable to: Hello from Mod" 

klass.hello_from_class #=> "Hello from Klass" 
klass.hello_from_module #=> nil (warning: instance variable @from_module not initialized) 
+1

変数は失われません。インスタンス変数はオブジェクト(インスタンス)に属します。そのため、インスタンス変数はインスタンス変数と呼ばれています。変数を設定しているインスタンスは何ですか?メソッドは 'Mod'のシングルトンメソッドなので、' self'は 'Mod'、インスタンス変数は' Mod'のインスタンス変数です。 –

+0

'return'はRubyに暗黙のうちに残されていることに注意してください。スタックに残された最後のものはデフォルトで戻り値です。したがって、メソッドの最後のものが戻り値として必要な場合は通常省略できます。 – tadman

答えて

2

あなたが記述何をすべきか、いくつかの方法があります。

最も一般的なものはinstance_variable_getinstance_variable_setを使用することです:

module ModA 
    def self.extended(base) 
    base.instance_variable_set(:@from_module, "Hello from Mod A") 
    puts "Setting variable to: #{base.instance_variable_get(:@from_module)}" 
    end 

    def hello_from_module 
    return @from_module 
    end 
end 

他の一般的な手法は、evalまたはexecのいずれかの方法を使用することです。この場合instance_exec

module ModB 
    def self.extended(base) 
    base.instance_exec { @from_module = "Hello from Mod B" } 
    puts "Setting variable to: #{base.instance_exec { @from_module }}" 
    end 

    def hello_from_module 
    return @from_module 
    end 
end 
関連する問題