sites
sites

Reputation: 21785

Logic equivalent for string comparison

Why are these expressions different:

!x == "string"

and

x != "string"

At least first expression does not enter my if, and when I change it, if code is executed.

Upvotes: 0

Views: 173

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

At least first expression does not enter my if

Here is my explanation :

! has higher precedence then ==. So in your expression !x == "string" will be internally represented as (!x) == "string"

!x either will be evaluted to true or false, which are TrueClass or FalseClass object respectively. Now Let's check whose #== method is used by true and false object.

true.method(:==).owner
# => BasicObject
false.method(:==).owner
# => BasicObject

Basic#== : Equality — At the Object level, == returns true only if obj and other are the same object.

As per the above definition your code !x == "string" should always be evaluated to false.

Upvotes: -2

vgoff
vgoff

Reputation: 11313

What do you expect "not x" to be? Will it be equal to "string" or any string for that matter?

It is simply a totally different statement.

You mention an if statement, so this must the condition that you are using for a logic statement. Since not x will never be equal to a string, then the if statements condition will always be false.

Upvotes: 2

Ju Liu
Ju Liu

Reputation: 3999

Let's say x is "foo"

!x == "string"

is expanded to

false == "string"

which is totally different from your second example, which is expanded to:

"foo" != "string"

Upvotes: 7

Related Questions