varatis varatis - 1 month ago 14
Ruby Question

How to check if an object is iterable in Ruby?

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.

Answer

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
Comments