Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Created August 17, 2012 02:23
Show Gist options
  • Select an option

  • Save keithrbennett/3375390 to your computer and use it in GitHub Desktop.

Select an option

Save keithrbennett/3375390 to your computer and use it in GitHub Desktop.
Solution to query_to_hash problem.
# This file is an rspec runnable file.
# (I didn't name it with _spec because its primary purpose is to provide
# the method, not run the test.)
# Here's the function that solves the problem, and the require needed to run it.
require 'uri'
def query_to_hash(query)
params = query.split('&')
params.inject({}) do |hash, expression|
key, escaped_value = expression.split('=')
unescaped_value = URI::unescape(escaped_value)
hash[key] = unescaped_value
hash
end
end
# Here's a simple rspec test that verifies the correctness of the provided example.
require 'rspec'
describe "Query to Hash" do
SAMPLE_STRING = "foo=bar&abc=1%202%203"
it "should return a hash containing the correct key/value pairs" do
expected = { "foo" => "bar", "abc" => "1 2 3" }
query_to_hash(SAMPLE_STRING).should == expected
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment