Extend Array instance with anoymous Module

It’s hacks like these that grow my appreciation of Ruby.

array = []
array.extend(Module.new{
	def append(value)
		value.is_a?(Array) ? replace(self|value) : replace(self|self<<value)
	end
})

In a plugin that mixes in functionality to many of my Rails models, I have a model array that I stick method names into. Some of the methods are preconfigured in the mixin itself. The rest are specified in the actual model after the mixin declaration.

Extending that single instance of Array with a method that eliminates duplicates and handles both individual values and entire arrays allows me to conveniently append.

One Comment

  1. Posted 5/12/2009 at 12:44 am | Permalink

    Finally some ruby!

Post a Comment

Your email is never shared. Required fields are marked *

*
*