URL format

I have the following hash myhash
{ “inter” => “team”, “shirt” => “stripe” }

desired output

inter=team&shirt=stripe

I tried url_for myhash but got undefined method `url_for’ for

thanks

On Mon, Sep 14, 2009 at 5:58 PM, Re BR [email protected] wrote:

I have the following hash myhash
{ “inter” => “team”, “shirt” => “stripe” }

desired output

inter=team&shirt=stripe

I tried url_for myhash but got undefined method `url_for’ for

The single line answer would be

hsh = { “inter” => “team”, “shirt” => “stripe” }
hsh.to_a.map{|e| e.join(‘=’)}.join(‘&’) # ‘inter=team&shirt=stripe’

Broken down

hsh = { “inter” => “team”, “shirt” => “stripe” }
ary = hsh.to_a #[[‘inter’, ‘team’], [‘shirt’, ‘stripe’]] - take the hash
and
switch into array
new_ary = ary.map{|e| e.join(‘=’)} #[‘inter=team’, ‘shirt=‘stripe’] -
take
the array and join the inner arrays using a =
final = new_ary.join(’&') # ‘inter=team&shirt=stripe’ take the remaining
array and join the element with &

John

Hi –

On Tue, 15 Sep 2009, John W Higgins wrote:

The single line answer would be

hsh = { “inter” => “team”, “shirt” => “stripe” }
hsh.to_a.map{|e| e.join(’=’)}.join(’&’) # ‘inter=team&shirt=stripe’

No need for the to_a. You’ll get a [key,value] array in e each time
through by just mapping the hash.

Note that the order might come out different; for example, on my
machine anyway:

hsh = { “inter” => “team”, “shirt” => “stripe” }
=> {“shirt”=>“stripe”, “inter”=>“team”}

hsh.map {|entry| entry.join("=") }.join("&")
=> “shirt=stripe&inter=team”

though I suspect it doesn’t matter in this case.

David

Hi,

Am Dienstag, 15. Sep 2009, 10:32:24 +0900 schrieb John W Higgins:

hsh = { “inter” => “team”, “shirt” => “stripe” }
hsh.to_a.map{|e| e.join(’=’)}.join(’&’) # ‘inter=team&shirt=stripe’

The correct way escapes the =' and&’ signs. I wrote my own
library and it seems that it doesn’t. Ugh.

Bertram

At 2009-09-14 09:40PM, “David A. Black” wrote:

hsh = { “inter” => “team”, “shirt” => “stripe” }
hsh.to_a.map{|e| e.join(’=’)}.join(’&’) # ‘inter=team&shirt=stripe’

hsh = { “inter” => “team”, “shirt” => “stripe” }
hsh.map {|entry| entry.join("=") }.join("&")
=> “shirt=stripe&inter=team”

I’m surprised that the URI module doesn’t have a method to handle it.

Hi,
I think I had faced the same issue before for encoding, I have used this
method for encoding urls.

require ‘rubygems’
require ‘rest-open-uri’
require ‘uri’
require ‘cgi’

def form_encoded(hash)
encoded = []
hash.each do |key, value|
encoded << CGI.escape(key) + ‘=’ + CGI.escape(value)
end
return encoded.join(’&’)
end

representation = form_encoded({ “user[name]” => username,
“user[password]” =>
password,
“user[full_name]”
=>
full_name,
“user[email]” =>
email
})

hope it will work for you…

Thanks and Regards
Saurabh P.
+91-9922071155
skype: sorab_pune
yahoo & gtalk: saurabh.purnaye
msn: [email protected]


Please don’t print this e-mail unless you really need to.

On Tue, Sep 15, 2009 at 8:44 AM, Bertram S.