Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Created November 14, 2013 04:47
Show Gist options
  • Save avanishgiri/7461534 to your computer and use it in GitHub Desktop.
Save avanishgiri/7461534 to your computer and use it in GitHub Desktop.
ruby solution for converting url into dictionary
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