On Mon, February 21, 2005 8:58 pm, mark sparshatt said:
> ES wrote:
>
>
>> I suppose the question is, then, is it necessary to have the above
>> behaviour?
>> As I understood it, the desired functionality was something like (my
>> syntax):
>>
>>  ob.not_nil?.do_something
>>
>> Conceptually expands to:
>>
>>  ob.do_something unless ob.nil?
>>
>> For this purpose, it should be sufficient to add a method to both Object
>> and NilClass. NilClass could then return an object that simply consumes
>> all methods fed to it and propagates itself after each call, like was
>> described in the original post as far as I can recall its contents. This
>> behaviour would then not be accessible except when using NilClass#not_nil?
>> so it wouldn't cause problems in other conditionals. Is there a use case
>> where this would cause a problem, or why is it desirable that the explicit
>> comparison be allowed for the special NIL and not just the chaining?
>>
>> Again, sorry if this has already been covered; feel free not to reply,
>> I'll read the NG in the evening. I'm just bored at work :)
>>
>>
>
> The problem with this solution is the new object won't behave like nil
> in an if expression
>
> if ob.not_nil?.do_something
>    code
> end
>
> would run the code when obj is nil

Ah. Overextending the idiom :) I'd say it works fine as a shortcut.
In the above scenario, if 'code' is a simple operation, one should
just do:

ob.not_nil?.do_something.code

Otherwise (or if 'code' is unrelated to the object), since we're
using a conditional *anyway*, one should do:

unless ob.nil?
  ob.do_something()
  code
end

So it's conceptually OK. The only issue is that it won't throw an error
if used incorrectly which may cause problems.

Now, a possible solution would be to cause NilClass#not_nil? to redefine
NilClass#method_missing and any other operation to clear the redefinition.
This would, unfortunately, prevent chaining except as follows:

ob.not_nil?.do_something.not_nil?.do_anotherthing

It's probably not thread-safe, though :)

> There seems to be 2 requirements
> the nil object shouldn't be changed, in order to not hide any errors
> the new nil object should behave like nil when tested
>
> that's why it can't be done in pure ruby
>
> Mark Sparshatt

E