URL format

R

Re BR

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
 
J

John W Higgins

[Note: parts of this message were removed to make it a legal post.]

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
 
D

David A. Black

Hi --

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:
=> "shirt=stripe&inter=team"

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


David
 
B

Bertram Scharpf

Hi,

Am Dienstag, 15. Sep 2009, 10:32:24 +0900 schrieb John W Higgins:
The single line answer would be

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
 
S

saurabh purnaye

[Note: parts of this message were removed to make it a legal post.]

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(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,917
Members
47,458
Latest member
Chris#

Latest Threads

Top