Ruby - Tests for Equality: == or equal?

Introduction

By default, a test using == returns true when both objects being tested are the same object.

So, it will return false if the values are the same but the objects are different:

ob1 = Object.new
ob2 = Object.new
puts( ob1==ob2 ) #=> false

In fact, == is frequently overridden by classes such as String and will then return true when the values are the same but the objects are different:

s1 = "hello"
s2 = "hello"
puts( s1==s2 ) #=> true

For that reason, the equal? method is preferable when you want to establish whether two variables refer to the same object:

puts( ob1.equal?(ob2) )    #=> false
puts( s1.equal?(s2) )          #=> false

Related Topic