On Sep 5, 2009, at 3:20 PM, Raul Miller wrote:

> On Sat, Sep 5, 2009 at 2:43 PM, Alan K. Stebbens<[email protected] 
> > wrote:
>> Many other computer languages deal with non-data just fine, some old,
>> some new:
>>
>>      SQL 92: NULL
>>        Ruby: nil
>>      Python: None
>> Objective C: nil
>
> With its nulls, though, basic rules of logic do
> not hold in SQL.
>
>> The nice thing about Ruby's OO methodology is that if you want to
>> extend a particular operator onto nil, you can:
>
> What happens when two different classes need different behavior
> from the same operator on nil?

that's fine.

The default behavior (to answer Roger's question), is that nil OP X  
returns nil in most cases.

We will be changing that behavior in two different class in two  
different ways.

For String, we'll treat nil as the empty string.
For Fixnums, we'll treat nil as zero.

   class String
     alias orig_cmp :<=>
     def cmp(v) # special-case "cmp" that coerces nils to ''
       self.orig_cmp(v.nil? ? '' : v)
     end
   end
   class Fixnum
     alias orig_cmp :<=>
     def cmp(v)  # special case "cmp" that coerces nils to 0
       self.orig_cmp(v.nil? ? 0 : v)
     end
   end

Here's the change in behavior for Fixnum:

> $ irb
> irb(main):001:0> 0 <=> nil
> => nil
> irb(main):002:0> class Fixnum
> irb(main):003:1>  alias orig_cmp :<=>
> irb(main):004:1*  def <=>(v)
> irb(main):005:2>   self.orig_cmp(v.nil? ? 0 : v)
> irb(main):006:2>  end
> irb(main):007:1> end
> => nil
> irb(main):008:0> 0 <=> nil
> => 0

Now see the change in behavior for String:

> irb(main):009:0> '' <=> nil
> => nil
> irb(main):010:0> class String
> irb(main):011:1>  alias orig_cmp :<=>
> irb(main):012:1*  def <=>(v)
> irb(main):013:2>   self.orig_cmp(v.nil? ? '' : v)
> irb(main):014:2>  end
> irb(main):015:1> end
> => nil
> irb(main):016:0> '' <=> nil
> => 0
>
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to