Stefano Crocco
7/24/2008 7:11:00 AM
On Thursday 24 July 2008, Sijo Kg wrote:
> Hi
> Could you please tell me when to use .nil? , .empty?, .blank? .What
> are the difference between them.. For example I have
> params[:company][:whichCompany]
> And to check for it is null I first attempted all these and finally the
> following worked
> if !params[:company][:whichCompany].empty?
>
> So now really i am confused .Please tell me the differnce
>
> Thanks in advance
> Sijo
nil? tests whether the receiver is the nil object, that is the only instance
of class NilClass, which is often used to indicate an invalid value. This
method is defined in class Object, and thus is availlable for every object.
The other two methods, instead, are defined only for specific classes, so the
answer depends. Usually, empty? is used to test whether an object is "empty",
for some class-depending meaning of empty. For example, String#empty? returns
true if the string contains no characters, Array#empty? and Hash#empty?
returns true if the array or hash has no entries. Other classes may define an
empty? method in other ways. Note that, unlike nil?, empty? isn't defined for
all classes.
Regarding blank?, I never heard of it, so I can't help you. You should look at
the documentation of the class defining it.
Here are some examples about nil? and empty?
nil.nil?
=> true
false.nil?
=> false
1.nil?
=> false
0.nil?
=> false
"".nil?
=> false
[].nil?
=> false
"".empty?
=> true
"abc".empty?
=> false
[].empty?
=> true
[1, 2, 3].empty?
=> false
1.empty?
=> NoMethodError
The last example means that the empty? method is not defined for class Fixnum
I hope this helps
Stefano