我可以拒绝不符合我的标准的对象,因为它们被输入到数组中吗?

blu*_*eys 1 ruby

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

例如

myArray = []
myArray + other_array
myArray << obj
myArray[index] = obj
Run Code Online (Sandbox Code Playgroud)

我也敢肯定,我可以使用.collect,.map,.concat,.fill,.replace,.insert,.join,.pack.push以及加入或修改的内容myArray.

但是,我想确保myArray只包含有效的HTTP/HTTPS URL.

任何人都可以解释我是如何强制执行这种行为的吗?

Phr*_*ogz 7

我将创建一个模块,允许您为数组指定接受块,然后覆盖您提到的所有方法(以及更多,如此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
Run Code Online (Sandbox Code Playgroud)