Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What is wrong with the "not" operator ? 1

Status
Not open for further replies.

mikrom

Programmer
Mar 27, 2002
2,985
SK
Now, I'm learning Ruby and I don't understand the difference between the logical negation operators ! and not.

If I try this assignment with the ! operator
Code:
irb(main):001:0> x = true
=> true
irb(main):002:0> t = !x
=> false
then it works, but this similar thing with not doesn' work
Code:
irb(main):001:0> x = true
=> true
irb(main):002:0> t = not x
SyntaxError: compile error
(irb):2: syntax error, unexpected kNOT
t = not x
       ^
        from (irb):2
irb(main):003:0> t = not(x)
SyntaxError: compile error
(irb):3: syntax error, unexpected kNOT
t = not(x)
       ^
        from (irb):3
Why I get the error unexpected kNOT ???

However using not in logical condition (without assignment) works good
Code:
irb(main):001:0> something = false
=> false
irb(main):002:0> if not(something)
irb(main):003:1>   puts "It is False"
irb(main):004:1> else
irb(main):005:1*   puts "It is True"
irb(main):006:1> end
It is False
=> nil
What is the difference between the operators ! and not? Who can explain this strange behaviour of the operator not?

 
Hi

mikrom said:
What is the difference between the operators ! and not?
[tt]![/tt] is a method and [tt]not[/tt] is an operator. At least according to this : Ruby Operator Precedence.

But your problem is just operator precedence :
Code:
irb(main):001:0> x = true
=> true
irb(main):002:0> t = [red]([/red]not x[red])[/red]
=> false

Feherke.
 
Thank you very much!

Did you mean that the precedence of the operator not is lower then the assignment =,
therefore we need to set it in parentheses?

 
Hi

Yepp. Apparently that is the situation. I would say, that operator precedence does not really match the POLS.

However, it has some logic if you used to put assignment for example in [tt]if[/tt] condition :
Code:
[b]if[/b] not result=myfairfunction : raise [i]'Gone bad'[/i] [b]end[/b]

process result

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top