Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 620
Alexandre Avatar asked Aug 19 '12 07:08

Alexandre


1 Answers

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?.

like image 98
Shailen Tuli Avatar answered Sep 19 '22 02:09

Shailen Tuli