Quickly Convert Hash Into URL Query
Here’s a rather quick and very short helpful Ruby trick that some of you might be interested in incorporating to your current or next project. It’s basically a snippet that makes use of the to_query method that’ll allow you to quickly convert a hash of values into a URL string.
"http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query # => "http://www.example.com?language=ruby&status=awesome"
And if you’d like to do it the other way around (in vice versa), you can use CGI.parse like so:
require 'cgi' # Only needed for IRB, Rails already has this loaded CGI::parse "language=ruby&status=awesome" # => {"language"=>["ruby"], "status"=>["awesome"]}
Both methods are said to support nested values. Credit and thanks goes to Victor Solis, the fellow who originally shared this nice trick.