Ruby attr_accessor :name 到 :name[] 数组
我将如何创建数组的 attr_accessor ?
例如
class MyClass
attr_accessor :my_attr_accessor
def initialize()
end
def add_new_value(new_array)
@my_attr_accessor += new_array
return @my_attr_accessor
end
end
my_class = MyClass.new
my_class.my_attr_accessor = 1
my_class.my_attr_accessor[1] = 2
my_class.my_attr_accessor.push = 3
my_class.add_new_value(5)
my_class.my_attr_accessor
=> [1, 2, 3, 5]
How would I create an attr_accessor to array?
for example
class MyClass
attr_accessor :my_attr_accessor
def initialize()
end
def add_new_value(new_array)
@my_attr_accessor += new_array
return @my_attr_accessor
end
end
my_class = MyClass.new
my_class.my_attr_accessor = 1
my_class.my_attr_accessor[1] = 2
my_class.my_attr_accessor.push = 3
my_class.add_new_value(5)
my_class.my_attr_accessor
=> [1, 2, 3, 5]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用一个指向数组的实例变量,并从该实例变量创建一个访问器。
在你的类中包含如下内容:
请注意,使用
attr_accessor
将允许你更改变量的值。如果要确保数组保留,请使用attr_reader
代替attr_accessor
。您仍然可以访问和设置数组元素并对数组执行操作,但无法将其替换为新值,并且使用+=
进行串联将不起作用。Just use an instance variable that points to an array and make an accessor from that instance variable.
Inside your class include something like this:
Note that using
attr_accessor
will allow you to change the value of the variable. If you want to ensure that the array stays, useattr_reader
in place ofattr_accessor
. You will still be able to access and set array elements and perform operations on the array but you won't be able to replace it with a new value and using+=
for concatenation will not work.如果您同意数组始终存在,@david4dev 的答案很好。如果您只希望数组在第一次使用时弹出,而不希望用户能够用新数组替换它(通过赋值):
用户仍然可以调用
my_class.my_attr_accessor。 Replace( [] )
将其删除。If you are OK with the Array always existing, @david4dev's answer is good. If you only want the array to pop into existence on the first usage, and never want the user to be able to replace it with a new array (via assignment):
The user could still call
my_class.my_attr_accessor.replace( [] )
to wipe it out.