"bar",:nasty => "Schrödinger cat"} p do_it(p...">

How to combine Hash parameters in URL?

quick Ruby request for you:

params = {:q => "A query",:foo => "bar",:nasty => "Schrödinger cat"} p do_it(params) => q=A%20query&foo=bar&nasty=Schr%C3%B6dinger%27s+cat 

(I think ö is encoded like this, sorry if it's wrong) Is there an easier way to do this than the following:

 def do_it(params) out = [] params.each_pair{|key,val| out.push "#{CGI.escape(key.to_s)}=#{CGI.escape(val)}" } out.join("&") end 

I'm not going to start a war for the “best” way to do this - its just this method seems very kludgey and un-ruby like it! Any tips?

+6
url ruby
source share
6 answers

Here's a shorter and more efficient method.

 def parameterize(params) URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&')) end 
+21
source share

use .to_param

 params = {:q => "A query",:foo => "bar",:nasty => "Schrödinger cat"} params.to_param => "foo=bar&nasty=Schr%C3%B6dinger%27s+cat&q=A+query" 
+6
source share

Rails does it for you.

 params = {:ids => [1,2], :query => 'cheese'} out = ActionController::Routing::Route.new.build_query_string(params) => "?ids%5B%5D=1&ids%5B%5D=2&query=cheese" 

which would be decoded: "? ids [] = 1 & amids; id [] = 2 & query = cheese"

+3
source share

You can make this a little easier by using collect :

 def do_it(params) params.collect do |key,val| "#{CGI.escape(key.to_s)}=#{CGI.escape(val)}" end.join('&') end 

I do not know how much more you can simplify it. Also note that CGI.escape converts spaces to + , not %20 . If you really want %20 , use URI.escape instead (you'll have to require 'uri' , obviously).

0
source share

I agree that this is a very "non-ruby-like" code. Although this is not much better, I think requestify () might be what you want:

http://www.koders.com/ruby/fid4B642EE4A494A744ACC920A1BE72CFE66D1D2B97.aspx?s=cgi#L291

0
source share

You should probably try following

 def to_query(key) "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" end 

copied from rail documentation . Remember to read the comments above the method definition.

0
source share

All Articles