尼爾對此有一個很好的答案,我只是想補充一點。
計數狗 :)
你需要一個類變量來做到這一點..
class Dog
@@count = 0 # this is a class variable; all objects created by this class share it
def initialize
@@count += 1 # when we create a new Dog, we increment the count
end
def total
@@count
end
end
還有另一種方式與「Class對象的實例變量」要做到這一點,但是這是一個一個高級話題位。
訪問實例變量
在Ruby中,變量是真正的對象/實例只是引用。
> x = 1
=> 1
> x.class
=> Fixnum
> 1.instance_variables
=> []
x是對象「1」的引用,它是類Fixnum的一個實例。 '1'對象是Fixnum的一個實例,它不包含任何實例變量。 從參考到新的「Dog」實例的方式並沒有什麼不同。
同樣,你可以說x = Dog.new
,那麼x是一個Dog類實例的引用。
class Dog
attr_accessor :legs # this defines the 'legs' and 'legs=' methods!
end
x = Dog.new
x.instance_variables
=> [] # if you would assign legs=4 during "initialize", then it would show up here
x.legs = 4 # this is really a method call(!) to the 'legs' method
x.instance_variables # get created when they are first assigned a value
=> [:legs]
如果你通過這樣的參考方法調用,或到其他類或只是通過自身評價它不要緊 - 紅寶石知道它是一個對象引用,並期待在物體內部和它的繼承鏈如何解決事情。
解析方法名稱
這只是部分真實:)當解釋x.legs
,紅寶石檢查是否存在對象的類的繼承鏈的方法,其響應於該名稱「腿」 。 這不是神奇地訪問具有相同名稱的實例變量!
我們可以通過做「attr_reader:legs」或「attr_accessor:legs」來定義一個方法'腿',或者通過自己定義方法來定義。
class Dog
def legs
4 # most dogs have 4 legs, we don't need a variable for that
end
end
x.legs # this is a method call! it is not directly accessing a :legs instance variable!
=> 4
x.instance_variables
=> [] # there is no instance variable with name ":legs"
,如果我們嘗試實現它作爲一種方法和實例變量,出現這種情況::)
class Dog
attr_accessor :legs # this creates "def legs" and "def legs=" methods behind the scenes
def legs # here we explicitly override the "def legs" method from the line above.
4
end
end
x = Dog.new
x.legs # that's the method call we implemented explicitly
=> 4
x.legs = 3 # we can still assign something to the instance_variable via legs=
=> 3
x.legs # the last definition of a method overrides previous definitions
# e.g. it overrides the automatically generated "legs" method
=> 4
attr_accessor :legs
就是這樣做的簡寫形式:
class Dog
def legs
@legs
end
def legs=(value)
@legs = value
end
end
沒有神奇的方式實例變量被自動訪問。它們總是通過一種方法訪問,稍後可以覆蓋它。
我希望對你有意義
好的,謝謝你非常有幫助。所以在我的例子中,當狗被實例化時,它在初始化和它的所有方法中被賦值。然而,直到應用程序/程序要求它與@ dog.popularity ...類似,流行性方法返回並與該實例關聯的值纔會對方法進行評估?就像我再次調用它會再次處理方法/關聯方法,還是隻知道它以前調用的值? – BC00 2013-03-07 21:15:16
它每次都被處理,它不記得。順便說一下,你通常不需要或者同時需要「attr_accessor:foo」和「def foo」 - 只是一個或另一個。如果你只想讀取和寫入實例變量,那麼attr_accessor是最簡單的。任何更復雜的東西,你想定義一個方法。 – 2013-03-07 21:18:46
真棒謝謝,這給我帶來了很多東西在一起 – BC00 2013-03-07 21:19:50