你能举个例子吗?
最佳答案
属性只是一个快捷方式。如果您使用 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"
关于ruby - Ruby 中的方法和属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194585/