How to get cookie value from CGI::Cookie.parse?

Viewed 116

How can I get a reasonable cookie value using only standard libraries from Ruby 2.7? According to the docs, #value is supposed to return a value or a list of values, but clearly it's not the case. c.value returns c

$ docker run --rm -it library/ruby:2.7
require 'cgi'
c = CGI::Cookie.parse('test=foo')['test']
# => #<CGI::Cookie: "test=foo; path=">
p c.value
# => #<CGI::Cookie: "test=foo; path=">
c.equal? c.value
# => true
# Please, what?

Expected result: foo (if www-encoded like %66%6f%6f, I want the decoded result foo).

1 Answers

The parent class of CGI::Cookie is Array. Now we can figure it out:

>> c = CGI::Cookie.parse('test=%66%6f%6f')['test']
=> #<CGI::Cookie: "test=foo; path=">
>> c.size
=> 1
>> c.first
=> "foo"
>> c[0]
=> "foo"
Related