Ruby中的相等:==,===,eql?,equal?,<=>

==,===,eql?,equal? 都有些啥区别

 

 

 

  • Equality (==, eql?, equal?)

 

 

==  普通的相等,不对object_id是否相等进行检查

eql? 和 ==  是相同的, equal?则是要对object_id是否相等进行检查

 

“test” == "test"  #=> return true,因为两者的值相等

“test"equal?("test") #=> return false  因为两者的值虽然相等,但两者的object_id不相等

 

 

  • Case Equlity ===

 

当使用‘case’ statement的时候,在ruby内部,会调用===方法

 

在case statement 外部使用的时候, Tripple Equal有两种不同的情况

如果是类来调用===方法,那么,就会比较另一个对象是否为当前类的实例

如果是对象调用===方法,那么,和==用法相同

 

 

String === "test"
# returns true because "test" is an instance of String

"test" === "test"
# returns true, because both objects have the same value or "==" returns true

"test" === "different test"
# returns false, because the two objects have different values.

 

 

在Ruby on Rails中, the Range class overrides “===” method to returns true if the compared value is found in the in the range values.(更正ruby中就可以,测试过ruby1.9.3)

 

 

1..10 === 1    # returns true
1..10 === 11   # returns false

case var
   when 1..10
       "do some stuff here"
   when 11..20
       "do something else here"
   else
       "out of range"
end

 

 

Source

 

 

补充:

  • <=>

Comparison—Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater thanother_ary. Each object in each array is compared (using <=>). If any value isn’t equal, then that inequality is the return value.

返回第一个不相等的元素的比较结果

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值