tags:

views:

451

answers:

4

Hi all, a quick Ruby question for you:

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

(I think ö encodes like that, excuse me if its wrong) Is there a simpler 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 looking to start a war over the 'best' way to do this - its just this method seems very kludgey and un-ruby like! Any tips?

A: 

You can make it a little bit simpler using collect:

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

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

Pesto
+3  A: 

Here's a shorter and more efficient method.

def parameterize(params)
  URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))
end
Mike Richards
Be sure to use this with `URI.escape` and not `CGI.escape` because the latter will turn that `=` into `%3D`.
Pesto
A: 

I agree that this is very "un-ruby-like" code. Although it's not much better, I think requestify() may be what you want:

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

Noah
A: 

You should probably try following

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

copied from rails documentation. Do not forget to read the comments above the method definition.

Waseem