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
current_user.notes
is already an array, meaning it already includes Enumerable, why do you need to do anything more? Your example can already run with a minor change:current_user.notes.inject(0) {|total_time_spent,note| total_time_spent + note.time_spent}
current_user.notes.sum(&:time_spent)