Alexandre
Alexandre

Reputation: 13308

How do I check parameter "param[:some_value]" in Ruby

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

Answers (4)

robustus
robustus

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

sawa
sawa

Reputation: 168101

The relevant cases are:

  1. The hash lacks the key (and its value)
  2. The hash has the value nil for the key
  3. The hash has the value empty string ("") or the empty array ([]) for the key
  4. The hash has some other value for the key

Depending on where you want to draw the line, use the appropriate method.

  • 1 vs. 2, 3, 4: !param.key?(:some_value)
  • 1, 2 vs. 3, 4: param[:some_value].nil?
  • 1, 2, 3 vs. 4: param[:some_value].blank?
  • 2, 3, 4 vs. 1: param.key?(:some_value)
  • 3, 4 vs. 1, 2: param[:some_value]
  • 4 vs. 1, 2, 3: param[:some_value].present?

Upvotes: 3

Shailen Tuli
Shailen Tuli

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

Michael Kohl
Michael Kohl

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

Related Questions