Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Enumerable mixin in my class?

Tags:

ruby

I have a class called Note, which includes an instance variable called time_spent. I want to be able to do something like this:

current_user.notes.inject{|total_time_spent,note| total_time_spent + note.time_spent} 

Is this possible by mixing in the Enumerable module? I know you are supposed to do add include Enumerable to the class and then define an each method, but should the each method be a class or instance method? What goes in the each method?

I'm using Ruby 1.9.2

like image 784
ben Avatar asked Aug 28 '11 11:08

ben


People also ask

What is enumerable in Ruby?

Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.

What is an enumerable method?

Enumerable methods work by giving them a block. In that block you tell them what you want to do with every element. For example: [1,2,3].map { |n| n * 2 } Gives you a new array where every number has been doubled.


1 Answers

It's easy, just include the Enumerable module and define an each instance method, which more often than not will just use some other class's each method. Here's a really simplified example:

class ATeam   include Enumerable    def initialize(*members)     @members = members   end    def each(&block)     @members.each do |member|       block.call(member)     end     # or     # @members.each(&block)   end end  ateam = ATeam.new("Face", "B.A. Barracus", "Murdoch", "Hannibal") #use any Enumerable method from here on p ateam.map(&:downcase) 

For further info, I recommend the following article: Ruby Enumerable Magic: The Basics.

In the context of your question, if what you expose through an accessor already is a collection, you probably don't need to bother with including Enumerable.

like image 186
Michael Kohl Avatar answered Oct 09 '22 19:10

Michael Kohl