Last active
December 28, 2015 07:09
-
-
Save avanishgiri/7461692 to your computer and use it in GitHub Desktop.
ruby solutions to problems 1 & 2.
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
##################################### P1 | |
def reverse(string) | |
string.length == 0 ? "" : string[-1] + reverse(string[0..-2]) | |
end | |
##################################### P2 | |
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.each { |k,v| hash[k] = v.first if v.length == 1 } | |
end | |
def url_to_dict(url) | |
scrub!(dict(tokenize(url))) | |
end | |
p reverse("1234") | |
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