Understanding the "||" OR operator in If conditionals in Ruby

The difference is the order of what's happening. Also the || isn't doing what you think it does in the 2 and 3.

You can also do

if ['projects','parts'].include?(@controller.controller_name)

to reduce code in the future if you need to add more matches.


the exact semantics of || are:

  • if first expression is not nil or false, return it
  • if first expression is nil or false, return the second expression

so what your first expression works out to is, if @controller.controller_name == "projects", then the expression short-circuits and returns true. if not, it checks the second expression. the second and third variants are essentially if @controller.controller_name == "projects", since "projects" || "parts" equals "projects". you can try this in irb:

>> "projects" || "parts"
=> "projects"

what you want to do is

if ["projects", "parts"].include? @controller.controller_name