On Mon, Mar 03, 2003 at 06:15:18PM +0900, Child wrote:
> On Mon, 3 Mar 2003 11:14:21 +0900, Yukihiro Matsumoto wrote:
> >|So I can't compare a date with nil, because I get an error. Instead I
> >|have to write something like date.instance_of? NilClass, which is
> >|something unnecessary complicated.
> >|
> >|Why is this implemented this way?
> > 
> > Why do you want to compare date with nil, when nil <=> date raises
> > NoMethodError?  Although it is better complied to other part of Ruby,
> > if it returns nil instead of raising exception.
> 
> Because in this specific case I don't know whether this variable is
> uninitialized (nil) or is a Date or something else. I write a database
> library and I check if the values I am inserting are not null. If they
> aren't, the only data type I have problem with is Date, because I can't
> compare it with nil.

I think that if foo <=> nil returned nil, it would have a number of
important and possibly undesirable knock-on effects. For example, what would
'sort' do when spaceship returns nil? Would foo < nil also end up returning
nil? What would happen if you tried to compare two other non-comparable
classes, e.g. 3 <=> true ?

You might find that one of the following patterns achieves what you want
without too much difficultly:

  <do something> unless foo.nil?  # shorter than 'foo.instance_of? NilClass'
  
  foo ||= SomeDefaultValue        # only assigns if foo==nil or false

Or you could use begin...rescue...end around the code section.

Regards,

Brian.