I wrote code for an Enumerables module:
module Enumerables
def palindrome?
if self.is_a?(Hash)
return false
else
self.join('').gsub(/\W/,"").downcase == self.join('').gsub(/\W/,"").downcase.reverse
end
end
end
The problem is, I have to write these:
class Array
include Enumerables
end
class Hash
include Enumerables
end
to make the code run successfully.
Is there an easy way to make the “palindrome?” method run with different instance types?
You could use the
ObjectSpace.each_objectiterator with a filter to find classes that include Enumerable and extend them dynamically:Now the trick is to write something that works for all enumerable types in a meaningful way! Note also that this sort of metaprogramming is fun for kicks but has serious implications if you plan to use it for anything other than “toy” programs.