tags:

views:

113

answers:

2

Beginning Ruby Question:

I'm trying to see if a string variable's contents is either "personal" "email" or "password".

I'm trying:

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

But that doesn't work and returns strange results, and using IRB to play around with "or" statements I have no idea why the following happens:

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 that if any of the 3 variables are true no matter what order they are in it returns true, if not it returns false. Anyone want to help this n00b out?

+13  A: 

This specific problem will have many good solutions, but instead I will concentrate on the boolean logic for educational purpose

You'll want to do this:

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

Programming languages aren't 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 it's common in mathematical notation to say:

"if a < b < c"

in most programming languages, you have to say:

if a < b and b < c

Let's see what happens with your experiment:

 a == "password" || "email"

Due to what is called "operator precedence", this is parsed as:

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

Now, since a == "email", this essentially evaluates to:

 false || "email"

which is why this expression evaluates to "email".

Similarly, with:

 a == "email" || "password"

This is essentially

 true || "password"

and that's why it evaluates to true.

polygenelubricants
+1: Ruby isn't COBOL. :)
JUST MY correct OPINION
You can also write "%w(password email whatever).include? a".
Chuck
PolyGeneLubricants: You are a king among men. There should be songs written and flowery prose inscribed to tell tales of your wisdom and spread the legend of your knowledge throughout the lands. Thanks for the help!
Kevin
Isn't there a Ruby equivalent of Python's `if x in (3, 5)`?
Alan
@Alan: I don't know Ruby enough to comment. As I said in the "preface", I was just focusing on explaining the `||` and why OP's experimentation resulted the way it did.
polygenelubricants
+5  A: 

The case statement is also good for matching this or that or ...

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