我有一个我需要转换为键值哈希的字符串。我使用Ruby 2.1和Rails 4.我使用了 @msg.body.split("&"),将字符串转换为数组。任何帮助都将受到赞赏。谢谢。
@msg.body => "longitude=-26.6446®ion_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®ion_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"
Hash[s.split("&").map {|str| str.split("=")}]
,变量s等于字符串:
s = "longitude=-26.6446®ion_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®ion_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"
这是您需要的吗?
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"}
由于您使用的是导轨,有两种方法:如果您不想收回数组,请执行以下操作:
# just putting your string in a var because I will reuse it
str = "longitude=-26.6446®ion_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®ion_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