How do I check if a variable is Enumerable in Ruby?

Sometimes, you’ll have a scenario where you’ll want to check and see if something can be enumerated or not. To do this, create a method like this:

def is_enumerable?(object)
object.is_a? Enumerable
end

To see how this works, lets pass in 2 objects - a string and a array.

[8] pry(main)> is_enumerable?("I'm a string")
=> false
[9] pry(main)> is_enumerable?(["array", "of", "things"])
=> true

And there you have a simple and easy way to check if something can be enumerated on!

Want more like this? Join the email list and get it delivered right to your inbox!



Join the newsletter

Subscribe to get my latest content by email.

    I won't send you spam. Unsubscribe at any time.