ruby:在附加到数组之前验证输入
我有一个ruby类,它的实例变量之一是数组。我试图弄清楚如何验证推送到阵列上的数据ruby:在附加到数组之前验证输入,ruby,arrays,validation,Ruby,Arrays,Validation,我有一个ruby类,它的实例变量之一是数组。我试图弄清楚如何验证推送到阵列上的数据 class Something def things @things ||= Array.new end end 这样我就可以很容易地声明一个实例并向数组中添加内容 @s = Something.new @s.things << "one" @s.things << "two" @s=Something.new @s、 事情尝试以下方式: things <<
class Something
def things
@things ||= Array.new
end
end
这样我就可以很容易地声明一个实例并向数组中添加内容
@s = Something.new
@s.things << "one"
@s.things << "two"
@s=Something.new
@s、 事情尝试以下方式:
things << data if valid?(data)
如果您想拥有自己的ThingsArray
只需创建一个数组
子类并覆盖推送(如何
class MyThings < Array
def << (item)
# do your validation with item
self.push(item) if item.valid?
end
end
class Something
def things(item)
@things ||= MyThings.new
end
end
类神话class ThingsArray < Array
def << (item)
return unless valid?(item)
super
end
private
def valid?(item)
item > 0
end
end
class Something
def things
@things ||= ThingsArray.new
end
end
class MyThings < Array
def << (item)
# do your validation with item
self.push(item) if item.valid?
end
end
class Something
def things(item)
@things ||= MyThings.new
end
end