属性只是一个捷径。如果你使用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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)