URL encoding

There's no reason for the hash.to_a bit - you can just do a hash.collect
straight off (without the !)

A more correct (unless I mangled something) example would be:

class String
  def urlencode
    gsub( /[^a-zA-Z0-9\-_\.!~*'()]/n ) {|x| sprintf('%%%02x', x[0]) }
  end
end
class Hash
  def urlencode
    collect do |k,v|
  "#{k.to_s.urlencode}=#{v.to_s.urlencode}" }.join('&')
    end
  end
end

There's probably somewhere in the stdlib that does the urlencode bit on
strings.

···

-----Original Message-----
From: Jonas Galvez [mailto:jonasgalvez@gmail.com]
Sent: Wednesday, 14 September 2005 3:11 PM
To: ruby-talk ML
Subject: URL encoding

Hi, is there any built-in function to convert

{:foo=>1, :bar=>2}

into

foo=1&bar=2

?

Shortest thing I could come up with was:

def urlencode(hash)
     hash.to_a.collect! { |k, v| "#{k}=#{v.to_s}" }.join("&") end

--Jonas Galvez

#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################

CGI.escape

···

On Sep 13, 2005, at 11:30 PM, Daniel Sheppard wrote:

There's probably somewhere in the stdlib that does the urlencode bit on
strings.