Why do `foo == bar` and` bar == foo` return different results?

What's going on here? Why ==

does the aspect ratio in comparison change the output?

secret == BCrypt::Password.new(BCrypt::Password.create(secret)) 
# => false 
BCrypt::Password.new(BCrypt::Password.create(secret)) == secret
# => true 

      

+3


source to share


4 answers


This is because the return value BCrypt::Password.new

has a value BCrypt::Password

that overrides==

http://bcrypt-ruby.rubyforge.org/classes/BCrypt/Password.html#M000009



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

So when secret

on the left its equals method is used (which does string comparison), whereas when the hash is on the left it actually compares to the original secret

+3


source


The simplest answer ==

is LHS#==

, yes , that is, ==

not a generic operator like in C or C ++ or Java, but rather a function called the left side object.

Without knowing more about your code, it's hard for you to tell exactly what's going on.



In simple terms, secret.class#==

should behave differently than BCrypt::Password#==

. Perhaps BCrypt :: Password knows how to compare an encrypted string (itself) and an unencrypted string (an argument), whereas secret

if it is a string, it doesn't know how to compare BCrypt::Password

with itself.

+1


source


BCrypt :: Password has a == method to compare against the secret.

BCrypt::Password.new(BCrypt::Password.create(secret)).class
 => BCrypt::Password 

      

So,

BCrypt::Password.new(BCrypt::Password.create(secret)) == secret
 => true

      

Another expression does not call the == method on BCrypt :: Password, but the one on the line.

http://bcrypt-ruby.rubyforge.org/classes/BCrypt/Password.html#M000009

+1


source


Ruby is an object oriented language. In OO, the recipient of a message sends a decision on how to respond to that message. In your case, the two receivers are not only different objects, but also different types of objects.

Ruby has several standard double-mailing protocols that are designed to enforce symmetry for some operators, but a) these protocols exist only for number arithmetic, not equality, and b) there is no guarantee that an object follows these protocols.

In short, there is no way in OO to enforce operator symmetry. It's just a fundamental property of OO.

0


source







All Articles