Ruby problems "||" "or"?

The beginning of the Ruby question:

I'm trying to figure out if the content of a string variable is "personal" "email" or "password".

I'm trying to:

if params[:action] == "password" || "email" || "personal"
  foo
else
  don't foo
end

      

But it doesn't work and returns strange results and using IRB to play with "or" statements I have no idea why the following is happening:

irb(main):040:0> a = "email"
=> "email"
irb(main):041:0> a == "password" || "email"
=> "email"
irb(main):042:0> a == "email" || "password"
=> true

      

I just want something, if any of the three variables are true no matter what order they are in, returns true if not return false. Anyone want to help this n00b?

+2


a source to share


3 answers


There will be many good solutions to this particular problem, but instead I will focus on logic boolean

for educational purpose

You will want to do this:

(a == "password") || (a == "email) || (a == "password")

      

Programming languages ​​are not like English: it has a strict grammatical rule and instead of saying:

"if x is 3 or 5"

      

in most programming languages, you have to say:

if x is 3 or x is 5

      

Similarly, where, as is customary in mathematical notation, one can say:

"if a < b < c"

      

in most programming languages, you have to say:

if a < b and b < c

      




See what's going on with your experiment:

 a == "password" || "email"

      

Due to what is called "operator priority" this is parsed as:

 (a == "password") || "email"

      

Now, since a == "email"

this essentially evaluates:

 false || "email"

      

so this expression evaluates to "email"

.

Similarly, with:

 a == "email" || "password"

      

This is essentially

 true || "password"

      

and therefore it evaluates true

.

+13


a source


The operator is case

also good for matching one or the other or ...



case email
when "password", "email", "whatever"
  puts "found a match: #{email}"
else
  puts "no match"
end

      

+5


a source


I sometimes use this version:

if ["password","email","personal"].include?(params[:action])
   foo
else
   don't foo
end

      

0


a source







All Articles