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

Viewed 95066

Just briefly, why are the following three lines not identical in their impact?

if @controller.controller_name == "projects" || @controller.controller_name == "parts"

if @controller.controller_name == ("projects" || "parts")

if @controller.controller_name == "projects" || "parts"

The first gives me the result I want, but as there's actually more options than just projects and parts, using that form creates a verbose statement. The other two are more compact, but don't give me the same result.

9 Answers

I see a lot of people preferring the include? comparison.

I prefer to use the .in? operator. It is much more succinct. And also more readable, since we don't ask questions to the array, we ask questions to the variable you want to ask: On your case, the controller name.

@controller.controller_name.in? ["projects", "parts"]

Or, even better

@controller.controller_name.in? %w[projects parts]
Related