如果要一边声明一边初始化可以用这样的代码:
[code]
class Object
def better_accessor(attrs)
(class << self; self; end).send :attr_accessor, *attrs.keys
attrs.each {|k,v| instance_variable_set("@#{k}", v)}
end
end
[/code]
然后就可以这样用:
[code]
class Test
def intialize
better_accessor :foo =>'bar' #初始化值即定死(值的正确性就自己保证了,用户只能通过setter改)
end
end
t = Test.new
t.foo #=> 'bar'
[/code]
或者先建对象后加属性,不用先定死值,但是用户可以在声明时绕过可能的setter验证,不安全:
[code]
t2 = Object.new
t2.better_accessor :hello =>'world'
t2.hello #=> 'world'
[/code]
[code]
class Object
def better_accessor(attrs)
(class << self; self; end).send :attr_accessor, *attrs.keys
attrs.each {|k,v| instance_variable_set("@#{k}", v)}
end
end
[/code]
然后就可以这样用:
[code]
class Test
def intialize
better_accessor :foo =>'bar' #初始化值即定死(值的正确性就自己保证了,用户只能通过setter改)
end
end
t = Test.new
t.foo #=> 'bar'
[/code]
或者先建对象后加属性,不用先定死值,但是用户可以在声明时绕过可能的setter验证,不安全:
[code]
t2 = Object.new
t2.better_accessor :hello =>'world'
t2.hello #=> 'world'
[/code]
本文介绍了一种在Ruby中实现自定义属性的方法,该方法允许在类定义时同时声明和初始化对象属性,提供了两种使用场景:一种是在对象创建时直接设置属性值;另一种是在对象创建后动态添加属性。
1091

被折叠的 条评论
为什么被折叠?



