Search code examples
rubyoperatorsbcryptequalitycommutativity

Is the order of the equality operator important in Ruby?


I have used the bcrypt library in my Ruby program. I noticed that the order of the equality operator seems to be important. Depending on which variable is left or right of the '==' I get a different result. Here is an example program:

require 'bcrypt'
my_pw = "pw1"
puts "This is my unhashed password: #{my_pw}"
hashed_pw = BCrypt::Password.create(my_pw)
puts "This is my hashed password: #{hashed_pw}"

20.times{print"-"}
puts

puts "my_pw == hashed_pw equals:"
if (my_pw == hashed_pw)
  puts "TRUE"
else
  puts "FALSE"
end

puts "hashed_pw == my_pw equals:"
if (hashed_pw == my_pw)
  puts "TRUE"
else
  puts "FALSE"
end

Regards schande


Solution

  • Yes, there is a difference.

    my_pw == hashed_pw calls the == method on the my_pw string and passes hashed_pw as an argument. That means you are using the String#== method. From the docs of String#==:

    string == object → true or false
    

    Returns true if object has the same length and content; as self; false otherwise

    Whereas hashed_pw == my_pw calls the == method on an instance of BCrypt::Password and passes my_pw as an argument. From the docs of BCrypt::Password#==:

    #==(secret) ⇒ Object
    

    Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise.