Good point.

Looked sort of handy in the log filter I produced to generate gnuplot  
files. Nil data has meaning in the plot, as distinct from a 0. It is  
also handy to treat a single result in the same way as an array  
result. The collation of the data, from the logs to the plot data  
file,  is being driven by an XML description, with embedded ruby  
expressions as XML attributes and text. These XML expressions get  
converted into methods to parse the logs.  Having the targets of the  
expressions work seamlessly, despite them being nil, single values or  
arrays, was quite neat.

In the nil case, I wanted it to iterate and be printed as in the same  
way as a non-nil value. In the plot data, a nil prints as '-'.  I  
hadn't thought of other code expecting to fail when the value was nil  
or not an array.  They probably wont want nil to have a to_s()  
returning  '-' either, not that anything has failed doing this, in  
this instance.

I am modifying it to output multiple rows, for generating Histograms,  
so I will look at doing this in a less dangerous way.

On 20/05/2006, at 12:20 PM, dblack / wobblini.net wrote:

> 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
>