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.

ScreenHunter 1531 Jan. 29 14.27 Quickly Convert Hash Into URL Query

"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.

 

 

Incoming search terms for the article:

Related Posts

Active Admin For Ruby On Rails

Creating a Psychedelic Art Effect in Your Portraits

Inspirational Photo Retouches By Cristian Girotto

Create Your Own Sticker Design Via Photoshop