我正在尝试用Ruby哈希url,但我有一些问题,我的url的大小从一个url到另一个不同,因此我的哈希键没有给我正确的结果。
我的url的两个例子
url1="Services/tech_name/prise/name_Prise/service_name/sites/xxxx/yyyy/devices/AAAA/wan/16170515?startDate=2021-01-18T23:00: 00.000Z&endDate=2021-01-19T08:22:42.000Z& timeProfile=1&tz=CET"
url2="Services/tech_name/prise/name_Prise/service_name/sites/xxxx/yyyy/devices/AAAA/BBBB/wan/1617051?startDate=2021-01-18T23:00: 00.000Z&endDate=2021-01-19T08:22:42.000Z& timeProfile=1&tz=CET"
哈希url1的代码示例:
url1="Services/tech_name/prise/name_Prise/service_name/sites/xxxx/yyyy/devices/AAAA/wan/16170515?startDate=2021-01-18T23:00: 00.000Z&endDate=2021-01-19T08:22:42.000Z& timeProfile=1&tz=CET"
spliturl=my_url.gsub("?","/")
url=spliturl.split("/")
if !url.count.even?
url.push(nil)
h=Hash[*url]
puts h
end
我结果:
{"Services"=>"name_services", "prise"=>"name_prise", "tech"=>"sites", "xxxx"=>"yyyy", "devices"=>"AAAA", "wan"=>"16170515", "startDate=2021-01-18T23:00:00.000Z&endDate=2021-01-19T08:22:42.000Z&timeProfile=1&tz=CET"=>nil}
"sites"已成为值还有"网站"值已成为键!!
{"tech"=>"sites", "xxxx"=>"yyyy", "devices"=>"AAAA", "wan"=>"16170515"}
但是我想从url1:
得到的结果{"sites" => "xxxx/yyyy", "devices" => "AAAA", "wan" => "16170515"}
and from url2:
{"sites" => "xxxx/yyyy", "devices" => "AAAA/BBBB", "wan" => "1617051"}
我有一个办法可以解决这个问题:
result = url1.match //sites/(?<sites>.*)/devices/(?<devices>.*)/wan/(?<wan>.*)?/
然后从结果中获取值:
result[:sites] => "xxxx/yyyy"
result[:devices] => "AAAA"
result[:wan] => "16170515"