2009-07-28 82 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将是一个属性。

相关问题