Ruby 3.1.2 kubuntu 22.04
从URL中提取基本域名(不包括子域名)的方法:
def host_name(a)
URI(a).host.sub(/\Awww\./, '')
end
用途:
uri_array = ['https://www.example.org', 'http://www.example.net/posts?a=1', 'www.example.com']
uri_array.map!(&method(:host_name))
预期yields :=>
['example.org', 'example.net', 'example.com']
相反会产生:
(irb):14:in `host_name': undefined method `sub' for nil:NilClass (NoMethodError)
所得数组如下修改:
[
[0] "example.org",
[1] "example.net",
[2] "www.example.com"
]
为什么它应该在数组的第三个元素上失败.