Ruby 在将不符合条件的对象输入数组时,是否可以拒绝这些对象?

Ruby 在将不符合条件的对象输入数组时,是否可以拒绝这些对象?,ruby,Ruby,我知道有很多方法可以在现有的ruby数组中创建新元素 e、 g myArray=[] myArray+其他_数组 myArray使用此选项插入。(未经测试) 使用此选项插入。(未经测试) 我将创建一个模块,允许您为数组指定接受块,然后覆盖您提到的所有方法(以及更多方法,如concat),以便在调用super之前预过滤参数。例如: module LimitedAcceptance def only_allow(&block) @only_allow = block end

我知道有很多方法可以在现有的ruby数组中创建新元素

e、 g

myArray=[]
myArray+其他_数组
myArray使用此选项插入。(未经测试)

使用此选项插入。(未经测试)


我将创建一个模块,允许您为数组指定接受块,然后覆盖您提到的所有方法(以及更多方法,如
concat
),以便在调用
super
之前预过滤参数。例如:

module LimitedAcceptance
  def only_allow(&block)
    @only_allow = block
  end

  def <<( other )
    super if @only_allow[ other ]
  end

  def +( other_array )
    super( other_array.select(&@only_allow) )
  end
end

require 'uri'
my_array = []
my_array.extend LimitedAcceptance
my_array.only_allow do |item|
  uri = item.is_a?(String) && URI.parse(item) rescue nil
  uri.class <= URI::HTTP
end
my_array << "http://phrogz.net/"
my_array << "ftp://no.way"
my_array += %w[ ssh://bar http://ruby-lang.org http:// ]
puts my_array
#=> http://phrogz.net/
#=> http://ruby-lang.org
模块限制验收
仅定义\u允许(&block)
@仅允许=块
结束

def我将创建一个模块,允许您为数组指定一个接受块,然后覆盖您提到的所有方法(以及更多方法,如
concat
),以便在调用
super
之前预过滤参数。例如:

module LimitedAcceptance
  def only_allow(&block)
    @only_allow = block
  end

  def <<( other )
    super if @only_allow[ other ]
  end

  def +( other_array )
    super( other_array.select(&@only_allow) )
  end
end

require 'uri'
my_array = []
my_array.extend LimitedAcceptance
my_array.only_allow do |item|
  uri = item.is_a?(String) && URI.parse(item) rescue nil
  uri.class <= URI::HTTP
end
my_array << "http://phrogz.net/"
my_array << "ftp://no.way"
my_array += %w[ ssh://bar http://ruby-lang.org http:// ]
puts my_array
#=> http://phrogz.net/
#=> http://ruby-lang.org
模块限制验收
仅定义\u允许(&block)
@仅允许=块
结束

def创建一个类来封装所需的行为。然后可以创建
创建一个类来封装所需的行为。然后您可以为URI.parse创建
+1并测试结果类(尽管我认为您的测试是向后的,并且您没有按照请求考虑https)。+1为URI.parse并测试结果类(尽管我认为您的测试是向后的,并且您没有按照请求考虑https)。
module LimitedAcceptance
  def only_allow(&block)
    @only_allow = block
  end

  def <<( other )
    super if @only_allow[ other ]
  end

  def +( other_array )
    super( other_array.select(&@only_allow) )
  end
end

require 'uri'
my_array = []
my_array.extend LimitedAcceptance
my_array.only_allow do |item|
  uri = item.is_a?(String) && URI.parse(item) rescue nil
  uri.class <= URI::HTTP
end
my_array << "http://phrogz.net/"
my_array << "ftp://no.way"
my_array += %w[ ssh://bar http://ruby-lang.org http:// ]
puts my_array
#=> http://phrogz.net/
#=> http://ruby-lang.org