Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4631

ruby 3.1: Using &method(:name) to simplify code fails inexplicably

$
0
0

ruby 3.1.2kubuntu 22.04

The method to extract the base domain name (excluding sub-domain) from a URI:

def host_name(a)  URI(a).host.sub(/\Awww\./, '')end

Use:

uri_array = ['https://www.example.org', 'http://www.example.net/posts?a=1', 'www.example.com']uri_array.map!(&method(:host_name))

expected output: =>

['example.org', 'example.net', 'example.com']

instead produces:

(irb):14:in `host_name': undefined method `sub' for nil:NilClass (NoMethodError)

with the resultant array modified like so:

[    [0] "example.org",    [1] "example.net",    [2] "www.example.com"]

Why it should fail on the 3rd element of the array.


Viewing all articles
Browse latest Browse all 4631

Latest Images

Trending Articles



Latest Images