How do I check if an object is iterable in Ruby?
That is, I want a method that cleanly checks if an object is iterable, like so:
def is_iterable(my_object) .. end
I'm really not sure where to start on this short of explicitly naming classes from within the method.
Edit: For my purposes, let's say iterable is something you can do .each to.
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.
respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example, @user.respond_to?('eat_food')
“Iterators” is the object-oriented concept in Ruby. In more simple words, iterators are the methods which are supported by collections(Arrays, Hashes etc.). Collections are the objects which store a group of data members. Ruby iterators return all the elements of a collection one after another.
For my purposes, let's say iterable is something you can do
.each
to.
You can just ask if this object has this method
def iterable?(object) object.respond_to?(:each) end
You already got some answers, but here are two more ways, Object#is_a?/Object#kind_of? and Module#===:
[].is_a? Enumerable #=> true "".is_a? Enumerable #=> false Enumerable === [] #=> true Enumerable === "" #=> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With