在红宝石中解析 [英] parsing in ruby
问题描述
我有这个Hash
:
cookie = {"fbs_138415639544444"=>["\"access_token=138415639544444|5c682220fa7ebccafd97ec58-503523340|9HHx3z7GzOBPdk444wtt&expires=0
&secret=64aa8b3327eafbfd22ba070b&session_key=5c682220fa7dsfdsafas3523340
&sig=4a494b851ff43d3a58dfa8757b702dfe&uid=503523340\""],
"_play_session"=>["fdasdfasdf"]}
我需要从access_token=
之后到&expires
之前的子字符串.问题在于,键fbs_138415639544444
中的数字每次都会更改,只是部分fbs_
保持不变.
I need to get the substring from right after access_token=
to right before &expires
. The problem is that the number in the key fbs_138415639544444
changes every time, just the part fbs_
remains constant.
任何想法如何获得:
"138415639544444|5c682220fa7ebccafd97ec58-503523340|9HHx3z7GzOBPdk444wtt"
推荐答案
这是解码HTML URL中的参数和查询时的常见任务.这是将参数分解为哈希的一种小方法.从那里很容易获得您想要的价值:
This is a common task when decoding parameters and queries in HTML URLs. Here's a little method to break down the parameters into a hash. From there it's easy to get the value you want:
def get_params_hash(params)
Hash[ *params.split('&').map{ |q| q.split('=') }.flatten ]
end
p get_params_hash(cookie['fbs_138415639544444'].first)['"access_token']
# >> "138415639544444|5c682220fa7ebccafd97ec58-503523340|9HHx3z7GzOBPdk444wtt"
在Ruby 1.9+中,哈希保留其插入顺序,因此,如果哈希始终具有您想要的值作为其第一项,则可以使用
In Ruby 1.9+, hashes retain their insertion order, so if the hash always has the value you want as its first entry, you can use
cookie.keys.first #=> "fbs_138415639544444"
否则使用:
cookie.keys.select{ |k| k[/^fbs_/] }.first #=> "fbs_138415639544444"
这篇关于在红宝石中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!