Ruby中的方法和属性有什么区别?
你能给我举个例子吗?属性只是一个快捷方式。如果使用Ruby中的方法和属性有什么区别?,ruby,attributes,methods,Ruby,Attributes,Methods,你能给我举个例子吗?属性只是一个快捷方式。如果使用attr\u 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
attr\u 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"
属性是对象的特定属性。方法是对象的功能 在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\u accessor
、attr\u writer
和attr\u reader
严格来说,属性是类实例的实例变量。在更一般的术语中,属性通常使用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中,这些方法是通过名称来表示的
通常情况下,“属性访问器”和基于属性值(如截断的_名称)提供数据的实用方法之间的差异很小,如示例中所示
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实例变量显式定义的gettercircle='是为@circle实例变量显式定义的setter。我听说在Ruby特定的圆中,“attribute”一词指的是任何不带参数的方法
class Batman
def favorite_ice_cream
[
'neopolitan',
'chunky monkey',
'chocolate',
'chocolate chip cookie dough',
'whiskey'
].shuffle[0]
end
end
在上面,my_New_batman.favorite_ice_cream将是一个属性。您始终可以使用Object.instance_variable_get(:@symbol)访问变量,这避免了定义访问器的需要。这不是一个很好的做法。;)实例_变量_get应该为元编程内容保留。这就像将一个方法定义为private,然后使用send(:method)访问它。