How would you parse a url in Ruby to get the main domain?

前端 未结 7 646
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 02:03

I want to be able to parse any url with ruby to get the main part of the domain without the www (just the XXXX.com)

7条回答
  •  鱼传尺愫
    2020-11-30 02:32

    Well you can write this method:

    require 'URI'
    def domain_name(url, arg={:with_dot_principal=>false})
      arg[:with_dot_principal] ? URI(url).hostname.split('.').last(2).join('.') : URI(url).hostname.split('.').last(2).first
    end
    

    And using:

    domain_name("https://www.google.com/?gws_rd=ssl&safe=active&ssui=on")
    # => "google"
    domain_name("http://google.com", with_dot_principal: true)
    # => "google.com"
    

提交回复
热议问题