2009-07-28 84 views

回答

28

屬性是對象的特定屬性。方法是對象的功能。

在Ruby中,所有實例變量(屬性)默認都是私有的。這意味着您無法在實例本身的範圍之外訪問它們。 訪問屬性的唯一方法是使用訪問器方法。

class Foo 
    def initialize(color) 
    @color = color 
    end 
end 

class Bar 
    def initialize(color) 
    @color = color 
    end 

    def color 
    @color 
    end 
end 

class Baz 
    def initialize(color) 
    @color = color 
    end 

    def color 
    @color 
    end 

    def color=(value) 
    @color = value 
    end 
end 

f = Foo.new("red") 
f.color # NoMethodError: undefined method ‘color’ 

b = Bar.new("red") 
b.color # => "red" 
b.color = "yellow" # NoMethodError: undefined method `color=' 

z = Baz.new("red") 
z.color # => "red" 
z.color = "yellow" 
z.color # => "yellow" 

因爲這是一個非常commmon行爲,Ruby提供了一些方便的方法來定義存取方法:attr_accessorattr_writerattr_reader

+1

您可以隨時使用Object.instance_variable_get(:@ symbol)訪問變量,該變量繞開了定義訪問器的需要。 – 2009-07-28 14:57:54

38

屬性只是一個捷徑。如果你使用attr_accessor創建一個屬性,Ruby只是聲明一個實例變量併爲你創建getter和setter方法。

既然你問了一個例子:

class Thing 
    attr_accessor :my_property 

    attr_reader :my_readable_property 

    attr_writer :my_writable_property 

    def do_stuff 
     # does stuff 
    end 
end 

這裏是你如何使用類:

# Instantiate 
thing = Thing.new 

# Call the method do_stuff 
thing.do_stuff 

# You can read or write my_property 
thing.my_property = "Whatever" 
puts thing.my_property 

# We only have a readable accessor for my_readable_property 
puts thing.my_readable_property 

# And my_writable_propety has only the writable accessor 
thing.my_writable_property = "Whatever" 
+3

我認爲這比答案的答案要好得多... – 2011-11-24 16:30:32

4

嚴格地說,屬性是類實例的實例變量。更一般地說,屬性通常使用attr_X類型方法來聲明,而方法只是簡單地聲明。

一個簡單的例子可能是:

attr_accessor :name 
attr_reader :access_level 

# Method 
def truncate_name! 
    @name = truncated_name 
end 

# Accessor-like method 
def truncated_name 
    @name and @name[0,14] 
end 

# Mutator-like method 
def access_level=(value) 
    @access_level = value && value.to_sym 
end 

的區別這兩者之間是用Ruby有點武斷,因爲是專門提供給他們沒有直接聯繫。這與C,C++和Java等其他語言形成鮮明對比,其中對象屬性和調用方法的訪問是通過兩種不同的機制完成的。特別是Java的accessor/mutator方法被拼寫出來,而在Ruby中,這些方法都是用名字來隱含的。

在例子中,通常情況下,「屬性訪問器」和提供基於屬性值的數據的實用程序方法(如truncated_name)之間的區別很小。

1
class MyClass 
    attr_accessor :point 

    def circle 
    return @circle 
    end 

    def circle=(c) 
    @circle = c 
    end 
end 

屬性是對象的屬性。在這種情況下,我使用attr_accessor類方法定義:point屬性以及用於point的隱式getter和setter方法。

obj = MyClass.new 
obj.point = 3 
puts obj.point 
> 3 

方法'circle'是一個顯式定義的@circle實例變量的getter。 'circle ='是@circle實例變量的明確定義的setter。

0

我聽說「屬性」這個詞在Ruby特定的圈子中引用了任何不帶參數的方法。

class Batman 

    def favorite_ice_cream 
    [ 
     'neopolitan', 
     'chunky monkey', 
     'chocolate', 
     'chocolate chip cookie dough', 
     'whiskey' 
    ].shuffle[0]   
    end 

end 

在上面,my_newest_batman.favorite_ice_cream將是一個屬性。

相關問題