Ruby将字符串转换为键值哈希值

时间:2014-02-01 21:44:32

标签: ruby

我有一个字符串,我需要转换为键值哈希。我正在使用ruby 2.1和rails 4.我使用@ msg.body.split(“&”)将字符串转换为数组。任何帮助表示赞赏。感谢。

@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"

3 个答案:

答案 0 :(得分:6)

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

其中变量s等于字符串:

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"

答案 1 :(得分:1)

这是你需要的吗?

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"}

答案 2 :(得分:0)

由于您使用的是rails,因此有两种方法: 如果您不想恢复阵列,请执行以下操作:

# 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

如果您需要数组,请执行以下操作:

require 'cgi'
CGI::parse(str)
# credit: http://stackoverflow.com/a/2773061/226255