New Discussion

Notifications

You’re not receiving notifications from this thread.

How to use Enumerable with Ruby Classes Discussion

1
General

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

Want to stay up-to-date with Ruby on Rails?

Join 90,918+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.