New Discussion

Notifications

You’re not receiving notifications from this thread.

How to use Enumerable with Ruby Classes Discussion

What use cases have you used Enumerable for?

You can include Enumerable in your class, but you’ll need to define an each method (yielding your elements). Then you’ll get all the Enumerable methods like map, select, etc., for free. For example:
class MyCollection
include Enumerable

def initialize(items)
@items = items
end

def each(&block)
@items.each(&block)
end
end
With that in place, MyCollection.new([1,2,3]).map { |i| i * 2 } works perfectly. Hope that helps!

Join the discussion
Create an account Log in