Hi --

On Sat, 20 May 2006, Rob Burrowes wrote:

> Excuse a newbee's enthusiasm, but this is really cool. It makes some code 
> that would have had to treat nil specially.
>
>
> class NilClass
> 	def each
> 		yield(self)
> 	end
> 	def length
> 		0
> 	end
> end
>
> a = nil
> a.each {|a| puts a.class }
>
> Doing it at the Object level is even more handy for the what I was playing 
> with.
>
> class Object
> 	def each
> 		yield(self)
> 	end
> 	def length
> 		if self == nil then 0 else 1 end
> 	end
> end
>
> a = nil
> a.each {|a| puts a.length }
>
> So every Object has an each method, which yields itself and has a length of 
> 1, so everything can be treated like an array.
> Really neat language.

Do be careful, though.  Remember that the changes you make to Object
and NilClass will be in effect for all the library code that you
include in your application, including the standard library, so if
anyone else is relying on the fact that some objects respond to "each"
and others don't, or that nil is dimensionless, something could go
wrong.


David

-- 
David A. Black (dblack / wobblini.net)
* Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
   > Ruby and Rails consultancy and training
* Author of "Ruby for Rails" from Manning Publications!
   > http://www.manning.com/black