开发者

Difference between <=> and == in Ruby?

What are their differences? Coming from a Java background, it doe开发者_开发问答s seem to me <=> is the same as Java's equals(), while == is for direct reference comparison. Is this right?


== only measures if two objects are equal, whereas <=> should return -1 if the first object is smaller, 0 if they are equal, and 1 if the first object is greater.

If you define a <=> method for your class, you'll get all of the other comparison operators defined as well (==, <, >, and so on).


Can't say I'm not trying to promote myself, but I wrote a full length tutorial about comparison and equality operators in Ruby: "Ruby Basics – Equality operators in Ruby"

In there you can see the differences between all the equality operators, including <=>, == and === (and the implications of implementing them, including the hash method implementation).


== is like Java's equals, while <=> is like compareTo. == compares the two objects and returns whether they are equivalent. a <=> b compares the two objects and returns 1 if a is bigger, 0 if they are the same and -1 if b is bigger.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜