From: dblack@... Date: 2006-10-06T20:42:45+09:00 Subject: Re: nil being empty Hi -- On Fri, 6 Oct 2006, David Chelimsky wrote: > On 10/5/06, Ohad Lutzky wrote: >> Show of hands - who thinks this is bad form? >> >> class NilClass >> def empty?; true; end >> end > > Doesn't it depend on context? The other responders seem to suggest > that is objectively bad form, with which I can agree (generally), but > in a case like this: > > collection.select do |item| > item.respond_to?(:empty?) and (!item.empty?) > end > > I might prefer > > collection.select do |item| > true unless item.empty? > end > > or this (which, though more terse, I personally find less readable) > > collection.select do |item| > !item.empty? > end (Don't forget Enumerable#reject :-) But "empty" actually means something, and it doesn't apply to all objects. (I mean, it *can*, if you define it, but it doesn't make sense.) I wouldn't know whether any of these objects were or were not empty: 10 98.6 String lambda { puts "hi" } etc. nil is in that category. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org