Empty nil
Posted on June 16, 2007 - Filed Under Ruby, RubyOnRails
Recently I have started to add one extension to Rubys NilClass, when creating new Rails application. It is empty? method. For me is obvious that result nil.empty? should be true. Adding such method allow to write:
if some_var_which_can_be_nil.empty? #code to handle nil/empty case end
Instead of
if some_var_which_can_be_nil.nil? || some_var_which_can_be_nil.empty? #code to handle nil/empty case end
Using first example without extending NilClass will result with NoMethod exception, when variable will be nil:
irb(main):001:0> nil.empty?
NoMethodError: undefined method `empty?' for nil:NilClass
from (irb):1
If in some case I would need to distinguish between nil and empty cases it can be done with check against nil in code handling nil/empty case. And of course NilClass extension is trivial:
class NilClass
def empty?
true
end
end
Result? More compact and clean code, which is good ;-)
Popularity: 5% [?]
Hits for this post: 2128
Similar Posts
- Iterating getMapTypes()
- Migrations with advanced data operations
- Uploading photos to Facebook with RFacebook
- Failing plugins discover
- Migrations headache
Comments
3 Responses to “Empty nil”
Leave a Reply




if some_var_which_can_be_nil.blank?
#code to handle nil/empty case
end
instead of
if some_var_which_can_be_nil.nil? || some_var_which_can_be_nil.empty?
#code to handle nil/empty case
end
It is always time to learn ;))
One word more - nil.blank? is Rails extension to Ruby!
In pure Ruby: