0

I have a string that I need to convert into a key value hash. I am using ruby 2.1 and rails 4. I used @msg.body.split("&") which converted the string to a array. Any help is appreciated. Thanks.

@msg.body => "longitude=-26.6446&region_name=xxxx&timezone=US/Central&ip=xxxxxxx&areacode=xxx&metro_code=xxx&country_name=United States&version=0250303063A&serial=133245169991&user_agent=Linux 2 XS&model=3100X&zipcode=23454&city=LA&region_code=CA&latitude= 56.1784&displayaspect=16x9&country_code=US&api_key=xxxxxxx&uuid=3489f464-2f9c-9c4c-d7d2-b51b7dd40ce3&event=appLoad&time_in_app=0"
kilomo
  • 249
  • 2
  • 6
  • 17

3 Answers3

7
Hash[s.split("&").map {|str| str.split("=")}]

where the variable s equals the string:

s = "longitude=-26.6446&region_name=xxxx&timezone=US/Central&ip=xxxxxxx&areacode=xxx&metro_code=xxx&country_name=United States&version=0250303063A&serial=133245169991&user_agent=Linux 2 XS&model=3100X&zipcode=23454&city=LA&region_code=CA&latitude= 56.1784&displayaspect=16x9&country_code=US&api_key=xxxxxxx&uuid=3489f464-2f9c-9c4c-d7d2-b51b7dd40ce3&event=appLoad&time_in_app=0"
Powers
  • 18,150
  • 10
  • 103
  • 108
1

Is this what you need?

Hash[@msg_body.scan /([^=]+)=([^&]+)[&$]/]

=>  {"longitude"=>"-26.6446",
   "region_name"=>"xxxx",
      "timezone"=>"US/Central",
            "ip"=>"xxxxxxx",
      "areacode"=>"xxx",
    "metro_code"=>"xxx",
  "country_name"=>"United States",
       "version"=>"0250303063A",
        "serial"=>"133245169991",
    "user_agent"=>"Linux 2 XS",
         "model"=>"3100X",
       "zipcode"=>"23454",
          "city"=>"LA",
   "region_code"=>"CA",
      "latitude"=>" 56.1784",
 "displayaspect"=>"16x9",
  "country_code"=>"US",
       "api_key"=>"xxxxxxx",
          "uuid"=>"3489f464-2f9c-9c4c-d7d2-b51b7dd40ce3",
         "event"=>"appLoad"}
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Since you're using rails, there are two ways: If you're don't want to get arrays back, do the following:

# just putting your string in a var because I will reuse it

str = "longitude=-26.6446&region_name=xxxx&timezone=US/Central&ip=xxxxxxx&areacode=xxx&metro_code=xxx&country_name=United States&version=0250303063A&serial=133245169991&user_agent=Linux 2 XS&model=3100X&zipcode=23454&city=LA&region_code=CA&latitude= 56.1784&displayaspect=16x9&country_code=US&api_key=xxxxxxx&uuid=3489f464-2f9c-9c4c-d7d2-b51b7dd40ce3&event=appLoad&time_in_app=0"

require 'rack'
Rack::Utils.parse_nested_query(str)
# credit: http://stackoverflow.com/a/2775086/226255

If you want arrays, do this:

require 'cgi'
CGI::parse(str)
# credit: http://stackoverflow.com/a/2773061/226255
Abdo
  • 13,549
  • 10
  • 79
  • 98