我有这个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"更多推荐
在红宝石中解析
发布评论