How to use enumerated mixin in my class?

I have a class called Note that 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 an Enumerable module ? I know that you have to add the include Enumerable class to the class and then define each method, but should each method be a class or instance method? What is included in each method?

I am using Ruby 1.9.2

+42
ruby
Aug 28 2018-11-11T00:
source share
2 answers

Easy, just include the Enumerable module and define an instance method each , which will most often use some other method of the each class. 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", "BA Barracus", "Murdoch", "Hannibal") #use any Enumerable method from here on p ateam.map(&:downcase) 

For more information, I recommend the following article: Ruby Enumerable Magic: The Basics .

In the context of your question, if what you open through the accessor is already a collection, you probably don't need to worry about enabling Enumerable .

+71
Aug 28 2018-11-11T00:
source share

The Enumerable docs state the following:

The enumerated mixin provides collection classes with several workaround and search methods, as well as the ability to sort. The class should provide every method that gives consecutive members of the collection. If Enumerable # max, #min or #sort is used, the objects in the collection must also implement the meaningful <=> operator, since these methods depend on ordering between members of the collection.

This means that each of them and <=> performs the trick.

See: Enumerable

+1
Oct 27 '17 at 9:06 on
source share



All Articles