Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the class of an underlying object in a Ruby enumerable?

Tags:

ruby

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

like image 570
B Seven Avatar asked Dec 04 '25 10:12

B Seven


1 Answers

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 [].

like image 191
Andrew Marshall Avatar answered Dec 06 '25 18:12

Andrew Marshall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!