> ## Enumerable ObjectSpace (#222)
>
> Kaixo Rubyists,
>
> This week's quiz was suggested by Trans[1].
>
> ObjectSpace has the method #each_object. I've always wanted to alias
> that to #each and make ObjectSpace Enumerable. But there's a catch,
> #each_object takes an argument and Enumerable does not pass arguments
> on to the #each method. So how does one resolve this issue? What's the
> easiest way to make ObjectSpace Enumerable?
>
> One could always take the brute force approach and completely
> re-implement Enumerable module to pass along the arguments. But I'm
> hoping there are much more elegant solutions to be had.



There is probably something better to be had using reflection and method
generation, but here's one stab:

class << ObjectSpace
  def method_missing(sym, *args, &block)
    mod  = args.first.is_a?(Module) ? args.shift : nil
    enum = enum_for(*[:each_object, mod].compact)
    enum.__send__(sym, *args, &block)
  end
end

# e.g. puts ObjectSpace.map(Class) { |c| c.name }

-- 
James Coglan
http://jcoglan.com