Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Last active December 28, 2015 07:09
Show Gist options
  • Save avanishgiri/7461692 to your computer and use it in GitHub Desktop.
Save avanishgiri/7461692 to your computer and use it in GitHub Desktop.
ruby solutions to problems 1 & 2.
##################################### 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