I want to redefine smalltalk's nil to work like the one in objective-c. So when nil receives a message that it can't handle, it returns nil. Now I know that nil
is just a shortcut for UndefinedObject
but is there anything like method_missing
in Ruby so I can redefine it in UndefinedObject
to always return nil?

- 13,134
- 6
- 58
- 106
3 Answers
The method you are looking for is called doesNotUnderstand:
in Smalltalk. You can indeed implement:
UndefinedObject>>doesNotUnderstand: aMessage
^ nil
However, keep in mind that this affects the complete system and might have subtle side effects or introduce bugs in other parts of the system.
Also note that UndefinedObject
is not a primitive type, but a normal class inheriting from Object
. Therefor nil
already understands a large number of messages and might not behave as you would expect coming from Objective-C.

- 8,754
- 23
- 46
-
Thank you! I'll look into it. I know that it can break the system, but I just want to try :) – Uko Apr 14 '12 at 20:03
Consider creating your own Null singleton class that implements #doesNotUnderstand: so that you don't modify nil. Make the super class nil (like Object).
Answer something like '^Null instance' instead of '^nil' in cases where you want it.
Null instance badMethod --> nil

- 366
- 1
- 3
- 10
-
that won't work. For example I want to close and destroy a connection. But if a new connection wasn't assigned to a variable, I'll send `close` to `nil` and I don't want to check if it's `nil` or not. I want to close it or do nothing. – Uko Apr 18 '12 at 09:48
-
1True... a null object is intended for your own code; it's a pattern we've found it useful. You can always add #orNull to UndefinedObject to answer null and to Object to answer self. Then your code could be 'x := self connection orNull'. – Bob Nemec Apr 19 '12 at 12:17
-
If you're the only person who will ever work on this code, I say go for it.
On the other hand, if this is a product owned by some company which is not a synonym for "you", and someone else may at some time have to maintain this, I strongly recommend that you NOT do this. Modifying classes at the heart of Smalltalk is one of THE classic ways to blow your toes off. (I knew a guy once who did this. He was not happy...and always limped a bit after that. Funny old thing, life...).
Share and enjoy.

- 48,992
- 9
- 77
- 110
-
Thanks, I know that stuff. I juts wanted to make some experiment, as I was doing my homework – Uko Apr 18 '12 at 17:29
-