Conditional statement style

This is a bit of a nuby question methinks but i’ve had a play/search
around and it’s just bugging me now :0)

Say I have a conditional statement, testing a variable against a number
of values. The first way i did this is like so:

if myvar != “” and myvar != 0 and myvar != nil

… code


This seems a bit messy - is there neater way of doing this? I thought

if myvar != ("" || 0 || nil)

but ||, as i understand it, is a conditional assigner that causes the
current value the fall through to the preceeding value, if the
preceeding value is nil. I’m sure that sentence made sense in my head
before i wrote it…

Anyway - any ideas would be appreciated,



Does the or statement work exactly the same as the || ?

if myvar != ("" or 0 or nil)

You could try:

unless ["", 0, nil].include?(myvar)


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs