if param[:some_value]
是最常见的一种。
但是,如果您使用的是布尔数据 ( true
, false
),最好的方法是if !param[:some_value].nil?
,因为:
>> hash = {foo:false, bar:nil}
>> !! hash[:foo]
=> false
>> !! hash[:bar]
=> false
>> !! !hash[:foo].nil?
=> true
>> !! !hash[:bar].nil?
=> false
(!!
returns the boolean value, which would be tested in an if-statement)
Also it could be important to test if the value is really nil, or if the key-value combo isn't defined. key?(key)
does that for you.
>> hash ={foo:nil}
>> hash[:foo]
=> nil
>> hash[:not_there]
=> nil
>> hash.key?(:foo)
=> true
>> hash.key?(:not_there)
=> false