Can't get "or" or "||" to work

Hi. I have a stupid question.

I’m stuck on the bit of ruby that follows:

name = gets.chop.downcase
if name != “bob” || “fred”
puts “That wasn’t one of the choices.”
else
code

If I put “bob” in it says:

That wasn’t one of the choices.

It does the same for anything I put in.

Thank you.

Use regular expressions instead

Joe

Sent from my iPad

Hi James,

You’re very close. This code should work:

name = gets.chop.downcase
if name != “bob” || name != “fred”
puts “That wasn’t one of the choices.”
else
code

You have to have a full expression for each part of the conditional.
What was happening previously was this:

The if statement checked the expression: name != bob
Then the is statement checked the expression: “fred”

In Ruby, anything that is not nil or false is considered true. Thus
“fred” is considered true.

I hope this has explained your problem :slight_smile:

Thanks,
Sam

Also, you will want to change || to &&. As it stands, you’re checking
that name is either not equal to “bob” or not equal to “fred”.
Whatever you put in there, it’s going to be not equal to one of them
:slight_smile:

Logic is tough to grasp at first but stick at it. It’ll become clear
if you practice!

what also work is:

unless [“bob”,“fred”].include?(name)

On 11/09/2011 09:02 AM, james gallagher wrote:

If I put “bob” in it says:

That wasn’t one of the choices.

It does the same for anything I put in.

Your logic is off. You’re wanting to see if name is either “bob” or
“fred”, right? Then you have to do:

if (name != “bob”) && (name != “fred”)

or, better still:

unless [“bob”, “name”].include? name

What you’ve written is trying to compare name to a boolean (specifically
the value of true) since “bob” || “fred” will be evaluated to a boolean
expression.

HTH.

Sam R. wrote in post #1031063:

Also, you will want to change || to &&. As it stands, you’re checking
that name is either not equal to “bob” or not equal to “fred”.
Whatever you put in there, it’s going to be not equal to one of them
:slight_smile:

Logic is tough to grasp at first but stick at it. It’ll become clear
if you practice!

Thank you so much.

This helped.

James.