Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does == do in Ruby?

Tags:

ruby

equals

In Java, == is the strongest kind of equality (pointer equality): a == b always implies a.equals(b). However, in Ruby, == is weaker than .equals?:

ruby-1.9.2-rc2 > 17 == 17.0
 => true 
ruby-1.9.2-rc2 > 17.equal?(17.0)
 => false

So, where can I learn more about ==? What kind of checks should I expect when I compare two objects with it?

like image 485
Trevor Burnham Avatar asked Aug 02 '10 17:08

Trevor Burnham


People also ask

What does == mean in Ruby?

This means… For example, by defining == you can tell Ruby how to compare two objects of the same class.

What does === means in Ruby Rails?

In Ruby, the === operator is used to test equality within a when clause of a case statement.

What is the == used for?

== operator The '==' operator checks whether the two given operands are equal or not. If so, it returns true.

What is the difference between == and equal in Ruby?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby. In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs.


2 Answers

briefly this is what you need to know:

The == comparison checks whether two values are equal

eql? checks if two values are equal and of the same type

equal? checks if two things are one and the same object.

A good blog about this is here.

like image 100
ennuikiller Avatar answered Oct 05 '22 10:10

ennuikiller


in reality they're both just methods == means object.==(other_object) equals? means object.equals?(other_object)

In this case, though, equals is used basically for hash lookup comparison i.e. a_hash[1] should not be the same key value pair as a_hash[1.0]

HTH. -r

like image 44
rogerdpack Avatar answered Oct 05 '22 09:10

rogerdpack