Created
August 17, 2012 02:23
-
-
Save keithrbennett/3375390 to your computer and use it in GitHub Desktop.
Solution to query_to_hash problem.
This file contains hidden or 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
| # 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