如何检查是否设置了哈希cookie值?

时间:2011-06-26 05:44:17

标签: ruby ruby-on-rails-3 cookies

通常我有:

cookies[:location] = { :value => { :city => 'foo', :country => 'bar' } } 

但是,有时:country未设置。当我这样做时:

cookies[:location][:country].present? 

要检查是否已设置国家/地区,则会返回错误:

[:country] is not a symbol

如果我不能这样做,我如何检查某个国家/地区是否设置在cookie[:location]

1 个答案:

答案 0 :(得分:3)

cookies哈希的嵌套方式与预期不同::value嵌套在:location下,:city:country嵌套在{{1}下}。以下是一些irb输出,可帮助您入门:

:value

如果您像下面那样嵌套哈希,您将获得预期的行为:

[~]$ irb
>> cookies={}
=> {}
>> cookies[:location] = { :value => { :city => 'foo', :country => 'bar' } }
=> {:value=>{:city=>"foo", :country=>"bar"}}
>> cookies[:location][:value][:country]
=> "bar"
>> cookies.to_s
=> "{:location=>{:value=>{:city=>\"foo\", :country=>\"bar\"}}}"