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 ;-)
Leave a Reply