如何将此字符串转换为哈希?

时间:2014-07-26 19:49:08

标签: ruby arrays string hash

以下代码将一些cookie数据作为字符串返回。

require 'httparty'

r = HTTParty.get('https://mijn.ing.nl/internetbankieren/SesamLoginServlet')

r.headers
# => {"date"=>["Sat, 26 Jul 2014 19:34:09 GMT"], "cache-control"=>["no-cache", "no-store"], "pragma"=>["no-cache"], "expires"=>["Thu, 01 Jan 1970 00:00:00 GMT"], "content-length"=>["13987"], "set-cookie"=>["sessiontype=mpb; Secure", "aac=742A83A50A4C422C24D6F952C4BF6355; Expires=Sun, 26 Jul 2015 19:34:08 GMT; Path=/; Domain=.ing.nl; Secure", "internetbankierenmi=1777182912.20480.0000; path=/", "TSdb640d=de34831032c17e8b66f123633372a9b341a9773368fccca553d402b1d4efbe89959deba9debace3fe0d47c86e27e0b6b1669bf05; Path=/"], "vary"=>["Accept-Encoding,User-Agent"], "content-type"=>["text/html;charset=ISO-8859-1"], "content-language"=>["en"], "connection"=>["close"], "strict-transport-security"=>["max-age=8640000"]}

response_cookies = r.headers['set-cookie']
# => "sessiontype=mpb; Secure, aac=742A83A50A4C422C24D6F952C4BF6355; Expires=Sun, 26 Jul 2015 19:34:08 GMT; Path=/; Domain=.ing.nl; Secure, internetbankierenmi=1777182912.20480.0000; path=/, TSdb640d=de34831032c17e8b66f123633372a9b341a9773368fccca553d402b1d4efbe89959deba9debace3fe0d47c86e27e0b6b1669bf05; Path=/"

我想将response_cookies字符串转换为我可以发送的Hash以及POST请求。

看起来应该是这样的:

{
  "sessiontype"=>"mpb", 
  "aac"=>"7430AEE30A4C42200A45ED316AA03490", 
  "Expires"=>"Sun, 26 Jul 2015 19:34:08 GMT", 
  "Path"=>"/", 
  "Domain"=>".ing.nl", 
  "internetbankierenmi"=>"1777182912.20480.0000", 
  "TSdb640d"=>"de34831032c17e8b66f123633372a9b341a9773368fccca553d402b1d4efbe89959deba9debace3fe0d47c86e27e0b6b1669bf05"
}

最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

您只需使用String#scan并将结果数组转换为哈希:

s.scan(/([^= ]+)=([^=;]+)(?=;|$)/).to_h
# => {"sessiontype"=>"mpb", "aac"=>"742A83A50A4C422C24D6F952C4BF6355", "Expires"=>"Sun, 26 Jul 2015 19:34:08 GMT", "Path"=>"/", "Domain"=>".ing.nl", "internetbankierenmi"=>"1777182912.20480.0000", "TSdb640d"=>"de34831032c17e8b66f123633372a9b341a9773368fccca553d402b1d4efbe89959deba9debace3fe0d47c86e27e0b6b1669bf05"}