1

I have an array:

ar = ["p=abhZRAh7Un", "a=2", "c=1", "l=3033102", "r=1", "rt=mr", "pid=136330865", "pdid=AiOIhH2vzMPqvhYkxXOxeA%3D%3D", "lks=54.0311", "fks=54.0311"]

and need to convert it into a hash with keys p, a, c, etc. and values – whatever is to the right of the equal sign. What is an elegant way to do that in ruby?

1
  • Show the code you've tried. Commented Jun 14, 2013 at 2:19

2 Answers 2

7
Hash[ar.map{|s| s.split("=")}]
2
  • That's hot. nice solution Commented Jun 14, 2013 at 0:23
  • be warned though: if your values may contain a '=' character, the split will not only split the string into key-value, but will split the value also! Unless you are aware of it and actually want that behaviour, you should add a LIMIT to the split. Commented Jun 14, 2013 at 13:41
2
require 'cgi'
ar = ["p=abhZRAh7Un", "a=2", "c=1", "l=3033102", "r=1", "rt=mr", "pid=136330865", "pdid=AiOIhH2vzMPqvhYkxXOxeA%3D%3D", "lks=54.0311", "fks=54.0311"]
CGI.parse(ar.join('&'))

outputs:

=> {"rt"=>["mr"], "fks"=>["54.0311"], "pid"=>["136330865"], "lks"=>["54.0311"], "pdid"=>["AiOIhH2vzMPqvhYkxXOxeA=="], "r"=>["1"], "l"=>["3033102"], "c"=>["1"], "a"=>["2"], "p"=>["abhZRAh7Un"]}
4
  • thank you, but I don't need each value to be an array. It should be a string. How to do that? I don't understand what exactly CGI.parse(ar.join('&')) does. Commented Jun 14, 2013 at 0:13
  • It's taking a URL querystring (in the URL for a GET you might see field1=value1&field2=value2&field3=value3.... and parsing it out as a hash. I thought it would be clever, but now I'm trying to get those arrays out of there.
    – 000
    Commented Jun 14, 2013 at 0:18
  • Actually, that might work for me as well. I know there will be just one element in this array, so it's OK. Thank you. Commented Jun 14, 2013 at 0:20
  • sawa's answer is better anyway. I have no idea why ruby decided to give me a hash of arrays. php's parse_str gives me a straight-up hash of values.
    – 000
    Commented Jun 14, 2013 at 0:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.