Skip to content

Instantly share code, notes, and snippets.

@sorokadima
Last active January 16, 2020 16:12
Show Gist options
  • Save sorokadima/baa76ebc1e4e6ed6e412371eaf079d1b to your computer and use it in GitHub Desktop.
Save sorokadima/baa76ebc1e4e6ed6e412371eaf079d1b to your computer and use it in GitHub Desktop.
Ruby add subdomain to URL
# WAY 1
url = 'https://www.example.com/post/hello-world'
subdomain = 'blog'
index = url.index('://www.') ? url.index('://www.') + 7 : url.index('://') + 3
url.insert(index, subdomain + '.')
p url
# WAY 2
url = 'https://www.example.com/post/hello-world'
subdomain = 'blog'
address = url.include?('://www.') ? url.partition('://www.').last : url.partition('://').last
url.gsub!(address, subdomain + '.' + address)
p url
# WAY 3
url = 'https://www.example.com/post/hello-world'
subdomain = 'blog'
url.include?('://www.') ? url.gsub!('://www.', "://www.#{subdomain}.") : url.gsub!('://', "://#{subdomain}.")
p url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment