How to split a URL into 2 parts in Ruby?

I have a ruby ​​script that downloads URLs from an RSS server and then downloads files at these URLs.

I need to split the URL into 2 components, for example:

http://www.website.com/dir1/dir2/file.txt
-->   'www.website.com'    and    'dir1/dir2/file.txt'

I'm struggling to find a way to do this. I played with regular expressions but nothing worked. How will others do this?

+3
source share
2 answers

Use the library URI.

require 'uri'
u = URI.parse("http://www.website.com/dir1/dir2/file.txt")
u.host
# => "www.website.com"
u.path
# => "/dir1/dir2/file.txt"
+16
source

A simple way is to use split.

split('/')[2]
+1
source

Source: https://habr.com/ru/post/1723650/


All Articles