我如何在我的班级中使用 Enumerable mixin? [英] How do I use the Enumerable mixin in my class?

查看:38
本文介绍了我如何在我的班级中使用 Enumerable mixin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Note 的类,其中包含一个名为 time_spent 的实例变量.我希望能够做这样的事情:

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}

这是否可以通过混合可枚举模块来实现?我知道您应该将 include Enumerable 添加到类中,然后定义一个 each 方法,但是每个方法应该是类还是实例方法?each 方法中有什么?

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?

我使用的是 Ruby 1.9.2

I'm using Ruby 1.9.2

推荐答案

很简单,只需包含 Enumerable 模块并定义一个 each 实例方法,通常比not 只会使用其他类的 each 方法.这是一个非常简单的示例:

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)

有关更多信息,我推荐以下文章:Ruby 可枚举魔法:基础.

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

在您的问题的上下文中,如果您通过访问器公开的内容已经是一个集合,您可能不需要费心包含 Enumerable.

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.

这篇关于我如何在我的班级中使用 Enumerable mixin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆