1

Is there any difference between these two statements:

! (name == "bob")

and

name != "bob"

To me, it seems like they both do the same thing. How are they different, if at all?

Nic
  • 6,211
  • 10
  • 46
  • 69
  • It is the same. It's like asking what's the difference between `5-1` or `5 + (-1)` – Martin Konecny Apr 26 '15 at 22:58
  • Are we asking about performance (there is a difference which could add up depending if we're just talking about strings or also different objects and implementations)? ... or are we talking about the end result (they are the same unless the `#!=` and `#==` methods aren't acting as expected)? – Myst Apr 27 '15 at 00:30

2 Answers2

4

They are almost the same.

  • ! (name == "bob") calls two methods ! and ==. you can write it like name.==('bob').!.
  • name != "bob" calls only one method !=. name.!=('bob').

Unless you redefine !=, you don't have to worry about these two options. In most cases, they are the same.

Here is an example how you can break it:

name = 'bob'
def name.!= s
  true
end
name.!=('bob') # => true
name.==('bob').! # => false

You may expect the first result to be false because the 'bob' on the left side (variable name) equals 'bob' on the right side, but it does not because the method is redefined.

sawa
  • 165,429
  • 45
  • 277
  • 381
Darek Nędza
  • 1,420
  • 1
  • 12
  • 19
0

Those would return the same result in any example I could think of, but placing the ! before the expression can be helpful when checking other things (e.g. !my_array.include?("bob").

Rob Mulholand
  • 899
  • 7
  • 7