2012-12-25 104 views
3

以下代碼不會打印任何內容,我期待welcomeBack。請解釋。實例變量聲明

class Hello 

    @instanceHello = "welcomeBack" 

    def printHello 
    print(@instanceHello) 
    end 

    Hello.new().printHello(); 
end 

我剛剛開始傾斜紅寶石,所以請原諒如果問題看起來愚蠢。

回答

7

如果你只能記住一個關於定義方法和設置變量的事情,那就是:總是問自己,現在什麼是self

class Hello 
    # This ivar belongs to Hello class object, not instance of Hello. 
    # `self` is Hello class object. 
    @instanceHello = "welcomeBack" 

    def printHello 
    # Hello#@instanceHello hasn't been assigned a value. It's nil at this point. 
    # `self` is an instance of Hello class 
    print @instanceHello 
    end 

    def self.printSelfHello 
    # Now this is [email protected] This is the var that you assigned value to. 
    # `self` is Hello class object 
    print @instanceHello 
    end 

end 

Hello.new.printHello # >> 
Hello.printSelfHello # >> welcomeBack 

如果要爲伊娃設定的默認值,這樣做在構造函數:

class Hello 

    def initialize 
    @instanceHello = "welcomeBack" 
    end 

    def printHello 
    print @instanceHello 
    end 
end 

Hello.new.printHello # >> welcomeBack 
+0

也許這只是我,但它似乎應該有一個「如果」在你的答案開始。 –

+0

@AndrewMarshall不只是你。我已經編輯了答案,把一個在:) – mikej

+0

謝謝你們,我忘了把它放在:) –

3

在Ruby中,實例變量的定義和實例方法使用。所以,你需要把在initialize方法你的任務:

class Hello 

    def initialize 
    @instanceHello = "welcomeBack" 
    end 

    def printHello 
    print(@instanceHello) 
    end 

end 

Hello.new.printHello(); 

另外請注意,我感動的類定義之外的printHello電話。這是因爲該類在第一次關閉之後才被實際定義;也就是最後的end之後。

0
class Hello 

    @instanceHello = "welcomeBack" 

    def printHello 
     puts self.class.instance_variable_get(:@instanceHello) 
    end 

    Hello.new.printHello; #=> welcomeBack 
end 

這不是很好的編程,只是爲了說明一個類(它是類類的一個實例)也可以具有實例變量,就像任何其他實例一樣。他們被稱爲「類實例變量」,並優於類變量。下面的示例示出了如何可以計數器在類層次進行定義:

class Hello 
    @counter = 0 

    class << self # access methods for class instance variables must be 
       # defined in the singleton class 
     attr_accessor :counter 
    end 

    def printHello 
     self.class.counter += 1 
     puts "Hello #{self.class.counter}" 
    end 
end 

Hello.new.printHello; #=> Hello 1 
Hello.new.printHello; #=> Hello 2 
p Hello.singleton_methods #=> ["counter=", "counter"] 
+0

_他們被稱爲「類實例變量」,並喜歡類變量。[[需要]?多年來一直使用Ruby,從未使用過「類實例變量」。當然,也沒有使用過很多類變量。 –

+1

@MarkHubbart其中,http://pragprog.com/book/ppmetr/metaprogramming-ruby解釋了類變量可以在整個類的層次結構中訪問,可以以不需要的方式進行修改,並得出結論:_因爲不受歡迎的意外如前所示,現在大多數Rubyists避免使用類實例變量的類變量._不是每天都使用,現在我用它來試圖使用類變量。 – user1852994

+1

heh。每天學些新東西。謝謝:) –

0

變化@instanceHello到self.class.instance_variable_get(:@ instanceHello)

@instanceHello是一個類的實例的變體

代碼是這樣的:

class Hello 
      @instanceHello = "welcomeBack" 
      @@classHello = "greeting!" 
      def printHello 
        print(self.class.instance_variable_get(:@instanceHello)) 
        print(self.class.class_variable_get(:@@classHello)) 
      end 
    end 
    Hello.new().printHello();