Reputation: 13308
I know some ways to check if parameter is not nil
if param[:some_value]
if param[:some_value].present?
if !param[:some_value].nil? #unless param[:some_value].nil?
if !param[:some_value].blank? #unless param[:some_value].blank?
Which one is correct and most popular? What is the difference between them?
I'd rather use if param[:some_value]
because it is simplest and shorterst.
Upvotes: 7
Views: 14731
Reputation: 3706
if param[:some_value]
is the most common one.
But if you're working with boolean data (true
,false
) the best method
would be if !param[:some_value].nil?
, because:
>> 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
Upvotes: 2
Reputation: 168101
The relevant cases are:
nil
for the key""
) or the empty array ([]
) for the keyDepending on where you want to draw the line, use the appropriate method.
!param.key?(:some_value)
param[:some_value].nil?
param[:some_value].blank?
param.key?(:some_value)
param[:some_value]
param[:some_value].present?
Upvotes: 3
Reputation: 14171
Here are some differences between nil?
, blank?
and present?
:
>> "".nil?
=> false
>> "".blank?
=> true
>> "".present?
=> false
>> " ".nil?
=> false
>> " ".blank?
=> true
>> " ".present?
=> false
Note that present?
translates to not nil and not blank
. Also note that while nil?
is provided by Ruby, blank?
and present?
are helpers provided by Rails.
So, which one to choose? It depends on what you want, of course, but when evaluating params[:some_value], you will usually want to check not only that it is not nil, but also if it is an empty string. Both of these are covered by present?
.
Upvotes: 15
Reputation: 66837
It depends what you want to do, but I generally use these forms:
if param[:some_value]
...
end
# and
param[:some_value] && something
# or
param[:some_value] || somethinn
Of course all of them only work if the parameter can't be false
. In that case I'd go for the unless param[:some_value].nil?
version.
Upvotes: 1