Ruby中的方法和属性有什么区别?
能给我举个例子?
属性是对象的特定属性。 方法是对象的function。
在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"
因为这是一个非常常见的行为,Ruby提供了一些方便的方法来定义访问器方法: attr_accessor
, attr_writer
和attr_reader
。
属性只是一种捷径。 如果使用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"
严格来说,属性是类实例的实例变量。 更一般地说,属性通常使用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)之间的差异很小。
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。
我听说过“属性”这个词在特定于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将是一个属性。