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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_enumerable?(object) | |
object.is_a? Enumerable | |
end |
To see how this works, lets pass in 2 objects - a string and a array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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!