Created
November 14, 2013 04:47
-
-
Save avanishgiri/7461534 to your computer and use it in GitHub Desktop.
ruby solution for converting url into dictionary
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
def tokenize(url) | |
url.split(/&/).map { |i| i.split(/=/) } | |
end | |
def dict(array_of_pairs) | |
array_of_pairs.inject(Hash.new{[]}) { |hash,pair| hash[pair.first] += [pair.last] ; hash } | |
end | |
def scrub(hash) | |
hash.map { |k,v| hash[k] = v.first if v.length == 1 } | |
hash | |
end | |
def url_to_dict(url) | |
scrub(dict(tokenize(url))) | |
end | |
p url_to_dict("a=1&b=2&a=hello&apple=9&apple=digital") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment