HeadFirst Ruby 第十章总结 Comparable & Enumerable
导言
这一章的标题是 Ready-Made Mixes, 也就是 Ruby 已经准备好的用于 Mix-in 的 Modules, 它们是: Comparable 和 Enumerable, Comparable 常用于比较数字, Enumerable 常用于 Collection 形式的数据.本章介绍了:
- 如何mix in Comparable 这个 Module
- 如何mix in Enumerable 这个 Module
如何使用 Comparable 这个 Module
定义:
Comparable 包含的 methods 有:
- >
- >=
- <
- <=
- ==
- between?
注意:在 Ruby 中,比较运算符的实质是数字类型数据对象(包含 Fixnum 和 Float 对象)的 method.
比如,4 > 3 的实质是 4调用了 .> (second_number ) 的方法,传入了 3 这个参数.
基础:定义 "<=>"这个 method
定义
<=> 名称叫做 "spaceship operator",它通过比较两边的值返回 -1, 0, 1 等值.
自我实现:
module Comparable
    def <(other)
        (self <=> other) == -1
    end
    
    def >(other)
        (self <=> other) == 1
    end
    
    def ==(other)
        (self <=> other) == 0
    end
    
    def <=(other)
        comparison = (self <=> other)
        comparison == -1 || comparison == 0
    end
    
    def >=(other)
        comparison = (self <=> other)
        comparison == 1 || comparison == 0
    end
    
    def between?(first, second)
        (self <=> first) >= 0 && (self <=> second) <= 0
    end
end
Comparable 包含的各种方法的基础是 "<=> 方法,它们是通过这个方法来进行运算并且给出判断值的.
如何使用 Enumerable 这个 method
定义
Enumerable 这个 module 包含的常见的 methods 有:
- find_all
- refuse
- map
总共包含了 50 个方法.
基础: each 方法
Enumerable 的基础是 each 这个 method ,因此需要在使用的 object 中创建 each 这个方法.
自我实现:
以分隔单词为例:
def each 
    string.split(" ").each do |word|
    yield word
    end
end
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号