Skip to content

Instantly share code, notes, and snippets.

@stuartellis
Created October 16, 2010 10:20
Show Gist options
  • Save stuartellis/629646 to your computer and use it in GitHub Desktop.
Save stuartellis/629646 to your computer and use it in GitHub Desktop.
A solution to the URL Splitter problem
# A solution to: http://sites.google.com/site/tddproblems/all-problems-1/URL-splitting
class UrlSplitter
def self.split(url)
match = url.match /(\w+):\/\/([^\/]+)(\/|$)(.*)?/
results = {:protocol => match[1], :domain => match[2]}
if match[4] == ""
results[:path] = nil
else
results[:path] = match[4]
end
results
end
end
@raul
Copy link

raul commented Oct 16, 2010

Well done! As a possible improvement, when you don't assign a value to a hash key, trying to access it evaluates to nil if you don't fill it with a value, so you could skip part of the if/else sentence:

results[:path] = match[4] unless match[4] == ""

Thanks for sharing your solution! :)

@stuartellis
Copy link
Author

That's much more elegant - thanks!

Alberto got the working regex, so he deserves the credit on this one :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment