2

Possible Duplicate:
Difference between “and” and && in Ruby?

I realized there are differences between and and && in Ruby (this was one confusing sentence).

@show_votes = !current_user.nil? and current_user.is_admin?
if @show_votes
  #code assumes everyone logged in is admin
end

Whereas:

@show_votes = !current_user.nil? && current_user.is_admin?
if @show_votes
  #code assumes only admin is admin
end

What is the difference between the two operators? I found that they have different operating precedence, but still can not figure out what the real difference is.

(the application was written with Rails. Although I would expect the same to occur in Sinatra as this is most likely something to do with the Ruby language)

edited the code to better reflect the situation.

Community
  • 1
  • 1
rickypai
  • 4,016
  • 6
  • 26
  • 30
  • http://www.tutorialspoint.com/ruby/ruby_operators.htm – sirmdawg May 18 '12 at 05:21
  • Your assumption is somewhat incorrect, but I am neither sure why that happens in your code. – SwiftMango May 18 '12 at 05:47
  • You can use symbolhound to search for syntax such as `and` and `&&`. – Andrew Grimm May 18 '12 at 05:50
  • Instead of doing `!current_user.nil? && ...` you could just do `current_user && ...` since `nil` evaluates to `false` (this is a fairly common Ruby idiom). – Andrew Marshall May 18 '12 at 05:55
  • well actually what happened was my colleague was using `@show_votes = !current_user.nil? and current_user.is_admin?` as a variable, and it would return true for logged in users regardless if the user is an admin. when doing `@show_votes = (!current_user.nil? and current_user.is_admin?)` or `@show_votes = !current_user.nil? && current_user.is_admin?`, it will only return true when the user is indeed an admin. – rickypai May 18 '12 at 07:42
  • I think the Ruby style guide https://github.com/rubocop-hq/ruby-style-guide#no-and-or-or is worth checking out about this issue (and how to avoid it). – wteuber Aug 15 '18 at 21:15

0 Answers0