I have this Hash
:
cookie = {"fbs_138415639544444"=>["\"access_token=138415639544444|5c682220fa7ebccafd97ec58-503523340|9HHx3z7GzOBPdk444wtt&expires=0
&secret=64aa8b3327eafbfd22ba070b&session_key=5c682220fa7dsfdsafas3523340
&sig=4a494b851ff43d3a58dfa8757b702dfe&uid=503523340\""],
"_play_session"=>["fdasdfasdf"]}
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.
Any idea how to only get:
"138415639544444|5c682220fa7ebccafd97ec58-503523340|9HHx3z7GzOBPdk444wtt"
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:
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
otherwise use:
Since the key changes, the first step is to get right key:
This matches them if they begin with the text "fbs_". The first match is returned.
Next you can get the other value by a few (ugly) splits:
Using a regex might be a bit cleaner, but it depends on what the valid characters are in that string.
I never code in ruby, but this sounds like a typical task for split function. you just need to split this
by & symbol. The first element of result array will be:
and after split it by =, and the second element of result array should be:
Regexs are brittle so I wouldn't use those when the reality is you are parsing query string params in the end so use the CGI lib:
This is how i solved the problem...
If you only need the
access_key
part, then a regex is probably easiest.Here the
access_key
is in the first capture group and you can get it with$1
.A better option if you'll need other parts of the string (say the
session_key
), would probably be to use a couplesplit
s and parse the string into it's own hash.Edit: Just realized you need the key too.
Then you can use
key
to get the value.