Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is iterable in Ruby?

Tags:

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.

like image 314
varatis Avatar asked May 25 '12 14:05

varatis


People also ask

How do you check the type of an object in Ruby?

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.

What is Respond_to in Ruby?

respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example, @user.respond_to?('eat_food')

What are iterators in Ruby?

“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.


2 Answers

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 
like image 183
Sergio Tulentsev Avatar answered Sep 20 '22 23:09

Sergio Tulentsev


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 
like image 36
Michael Kohl Avatar answered Sep 19 '22 23:09

Michael Kohl