Bug #9081

Unexpected result for and opreator

Added by Mo Amin 6 months ago. Updated 6 months ago.

[ruby-core:58162]
Status:Rejected
Priority:Normal
Assignee:-
Category:-
Target version:-
ruby -v:ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin11.4.2] Backport:1.9.3: UNKNOWN, 2.0.0: UNKNOWN

Description

I use this code to test and confirm this result

def show
@profile = .......
puts "=================="
puts usersignedin?
puts currentuser.id
puts @profile.user.id
puts user
signedin? and (currentuser.id == @profile.user.id)
puts true and (1 == 2)
puts true and false
puts true && false
puts "=================="
.......
end

this is console output

User Load (0.6ms) SELECT users.* FROM users WHERE users.id = 3 ORDER BY users.id ASC LIMIT 1
true
3
User Load (0.4ms) SELECT users.* FROM users WHERE users.id = 11 ORDER BY users.id ASC LIMIT 1
11
true
true
true

false

the last two lines will clear the problem, I except and, && is the same !

ruby -v ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin11.4.2]
rails -v Rails 4.0.0

Screen Shot 2013-11-05 at 2.21.40 AM.png (38.5 KB) Mo Amin, 11/05/2013 09:41 AM

History

#1 Updated by Gergo Erdosi 6 months ago

This isn't unexpected behavior. (({and})) and (({or})) are not boolean, but control flow operators. Execution stops when an operation returns (({nil})) or (({false})). Use (({&&})) or (({||})) for the desired behavior.

#2 Updated by Charlie Somerville 6 months ago

  • Status changed from Open to Rejected
  • Priority changed from High to Normal

This isn't a bug. The 'and' operator has lower precedence than '&&', so when you write this code:

puts true and false

It's parsed as:

puts(true) && false

If you instead write:

puts true && false

Then Ruby will parse this expression like this, as you intend:

puts(true && false)

Also available in: Atom PDF