O
O
Ord EO2020-08-05 16:28:40
ruby
Ord EO, 2020-08-05 16:28:40

How to get part of a string in ruby?

There is a line
string = 'https://qna.habr.com/question/new'You need to get everything between the slashes with the help of ruby, in this case it should work qna.habr.com
if the site came in this form qna.habr.com/question/newanyway, get it anyway , qna.habr.com
or if qna.habr.comit doesn’t matter. qna.habr.com

Advise how this can be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artur Bordenyuk, 2020-08-05
@OrdeO

Certainly

require 'uri'

def extract_domain(url)
  url = "http://#{url}" if URI.parse(url).scheme.nil?
  URI.parse(url).host.downcase
end

extract_domain('https://qna.habr.com/question/new') #=> qna.habr.com
extract_domain('qna.habr.com/question/new') #=> qna.habr.com
extract_domain('qna.habr.com') #=> qna.habr.com

How else can we help?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question