Last active
January 16, 2020 16:12
-
-
Save sorokadima/baa76ebc1e4e6ed6e412371eaf079d1b to your computer and use it in GitHub Desktop.
Ruby add subdomain to URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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