==,===,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
补充:
- <=>
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.
返回第一个不相等的元素的比较结果