Reputation: 45943
a = [4, 5, 3]
e = a.each
e.class #=> Enumerator
e.first.class #=> Fixnum
How do you find out if e is an enumerator for an array, hash or other type?
Working in Ruby 1.9.2
Upvotes: 3
Views: 74
Reputation: 2059
Not that I propose that this is appropriate or in any way a good idea, but you CAN inspect an enumerator and potentially get some information that would give you a hint to the underlying object. This of course, begs the question of why you would want to do this...
a = [1,2,3,4]
=> [1, 2, 3, 4]
e = a.each
=> #<Enumerator: ...>
e.inspect
=> "<#Enumerator: [1, 2, 3, 4]:each>"
a = { :foo => "bar" }
=> {:foo=>"bar"}
e = a.each
=> #<Enumerator: ...>
e.inspect
=> "#<Enumerator: {:foo=>\"bar\"}:each>"
You can then use a regexp to try to tease out information about the underlying object. There are probably occasions for which this won't work (it does work for ranges). I'd emphasize again that there's probably no good reason to do this.
Upvotes: 1
Reputation: 11705
I would tentatively say that this can't be done. There doesn't seem to be any requirement, when creating an Enumerator, to actually reference the source object itself, only to tell the Enumerator how to get to the next, current, etc... values
Upvotes: 0
Reputation: 96934
You can't (easily).*
Nor should you be able to. Enumerators aren't meant to care about what's contained within them, they're meant to iterate over something. You probably shouldn't be passing around enumerators anyway: just pass around the actual object.
Though, you could do nasty things like parse [].each.inspect
with regex for either []
or {}
, or the case where it's another type like #<Set: {}>
. But this is just so horrible. I suggest re-thinking why you want to do this—and then not doing it.
* Note that the non-easy programmatic way would be to write C code using the Ruby C API and tap into the actual object pointer within the enumerator. This needs to be done because Enumerator is written in C, and causes doing things like [].each.instance_variables
to return []
.
Upvotes: 4