nil.blank?
Friday, September 28th, 2007C2 Wiki discusses how nil.to_s.empty?
is available in rails and nil.blank?
is provided for Ruby On Rails,
Ruby
[source:ruby]
nil.to_s.empty?
>> true
[/source]
Rails
[source:ruby]
nil.blank?
>> true
[/source]
Java
[source:Java]
String s = null;
return s == null;
>> true
[/source]
Let’s say we want to check that s is non-blank string. The danger is that s could be null. We will use random to seed s (Or just think of it as the invisible hand typing a form value). In ruby we can do:
[source:ruby]
s = rand < 0.5 ? “” : nil
!s.blank?
>> true
[/source]
And in java?
[source:Java]
String s = Math.random() < 0.5? “” : null;
return !s.equals(“”); //Playing roulette
>> NullPointerException?!
if (s!=null) {
return !s.equals(“”);
} else {
return false;
}
>> true
[/source]
Verbosity, or simplicity? I feel that in web development where checking for blanks occur on a frequent basis, ruby has the better syntax. Not just in length, but it fits with my mental context as well.