Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 18 ’12

Quick Hash to a URL Query trick

Got a hash of values you want to convert into a url query string? Use the to_query method:

"http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query
# => "http://www.example.com?language=ruby&status=awesome" 

Want to do it in reverse? Use CGI.parse:

require 'cgi' # Only needed for IRB, Rails already has this loaded
CGI::parse "language=ruby&status=awesome"
# => {"language"=>["ruby"], "status"=>["awesome"]} 

Both methods support nested values.

This tip was submitted by Victor Solis.

13 notes 0 comments

  1. texasworkshop said: texasminiatureshowcase….
  2. bikeshed-blog reblogged this from rubyquicktips
  3. tex reblogged this from rubyquicktips
  4. Victor Solis submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus