Ruby Ruby 中的四种等价操作符

ping94 · 2018年06月09日 · 1250 次阅读

每定义一个类时,它们都继承了四个不同的等价性检查方法,理解其工作方式才能帮助你在需要的时候更好的重载它们

1、equal?

检测是否为同一对象 (具有相同的 object_id)

2、eql?

  • 比较是否为相同的类型和相等的值
  • 当为自定义的类时,其默认的行为与 equal?相同
  • Hash 在冲突检测时使用 eql?来比较键对象

当使用对象为 hash 的键时,如果希望两个相似的对象具有相同的哈希键时需要同时实现 hash 和 eql?两个方法

class Color
    attr_reader :name
    def initialize(name)
        @name = name
    end

    def hash
        name.hash
    end

    def eql?(o)
        name.eql?(o.name)
    end
end

3、==操作符

  • 比较两个对象的值是否相同
  • 两个数字使用时操作符会将对象做类型的隐式转换
irb> 1 == 1.0
---> true

4、 ===操作符

  • === 默认行为只是将对象传给 ==
  • 某些类重新定义了 === 方法,如 Regexp(正则表达式匹配)
irb> /er/ === 'typer'
---> true
irb> 'typer' === /er/
---> false
  • 类和模块也重新定义了 === 方法
irb> [1,2,3].is_a?(Array)
---> true
irb> Array === [1,2,3]
---> true
irb> [1,2,3] === Array
---> false
  • case 表达式使用 === 来测试每个 when 语句的值,左操作数是 when 的参数,右操作数是 case 的参数
case command
when 'start' then start
when 'stop', 'quit' then stop
when /^cd\s+(.+)$/ then cd($1)
when Numeric then timer(command)
else rails error
end

等价于

case command
if 'start' === command then start
elsif 'stop' === command then stop
elsif 'quit' === command then stop
elsif /^cd\s+(.+)$/ === command then cd($1)
elsif Numeric === command then timer(command)
else rails error
end
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号