了解可比的mixin和可枚举的mixin [英] understanding comparable mixin and enumerable mixin

查看:127
本文介绍了了解可比的mixin和可枚举的mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,正在学习红宝石.希望对提出的问题有更好的理解.我不明白可比的mixin和可枚举的mixin的用法.我的意思是我们在需要使用它们时不将其包含在我们的课程中,对吗?如果我们想比较两个对象,我们只需写x> y即可.那么显式使用它们的用途是什么?

I am a newbie and learning ruby. Would like to have a better understanding of the question asked. I don't understand the use of comparable mixin and enumerable mixin. I mean we don't include these in our class when we need to use them, right? if we want to compare two objects we simply write x > y. Then what is the use of explicitly using them?

推荐答案

大问题阿卡什!

有时候,比较两个对象不是简单"的事情!如果您有狗课怎么办?您如何比较两个Dog实例?比较应该基于什么?比较他们的名字就足够了吗?他们的品种?他们的DNA?这完全取决于您.那就是您可以在模型中包括Comparable并实现自己所需的最小功能,以定义使两个Dog实例相同的原因.您定义比较.一旦在模块中定义了< =>比较器,就可以对对象进行相等性比较或对对象进行排序或排序,因为ruby知道如何将一个实例与另一个实例进行比较.

Sometimes it's not "simple" how two objects can be compared! What if you have a Dog class? How do you compare two Dog instances? What should be the comparison based on? Is it enough to compare their name? their breed? their DNA? It's really upto you. And thats when you can include Comparable in your model and implement the minimum function necessary yourself to define what makes the two Dog instances the same. You define the comparision. Once you have defined the <=> comparator in your module, your object can then be compared for equality or be sorted or ordered because ruby will know HOW to compare one instance against another.

类似地,包含Enumerable模块使您的类能够遍历其实例的集合.一旦在类中实现了每个方法,您就可以在类中获得整个Enumerable模块的方法.可以在您的课程上使用诸如map/collect等方法.

Similarly, including the Enumerable module allows your class the ability to iterate over a collection of its instances. Once you implement the each method in your class, you get the whole Enumerable module's methods available in your class. Methods such as map/collect etc can be used on your class.

class Dog
  include Enumerable

  attr_accessor :puppies, :name

  def initialize(name)
    @name = name
    @puppies = []
  end

  def each(&block)
    @puppies.each do |puppy|
      puts "yielding #{puppy}"
      yield(puppy)
      puts "just yielded #{puppy}"
    end
  end

end


tommy = Dog.new("tommy")
tommy.puppies = ["julie","moti","husky"]

tommy.each do |p|
  puts p
end

big_puppies = tommy.map{|x| x.titleize }

这篇关于了解可比的mixin和可枚举的mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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