Biketire Biketire - 1 year ago 68
Ruby Question

Can an "if (a == b || c == b)" statement be done shorter in Ruby

I have a piece of code in Ruby which goes as follows:

def check
if a == b || c == b
# execute some code
# b = the same variable

can this be written like

def check
if a || c == b
# this doesn't do the trick
if (a || c) == b
# this also doesn't do the magic as I thought it would

Or in a manner where I don't need to type
twice. This is out of laziness and I would like to know.

Answer Source
if [a, c].include? b
  # code

This is, however, significantly slower than the code you want to avoid -- at least as long as a, b and c are basic data. My measurements showed a factor of 3. This is probably due to the additional Array object creation. So you might have to weigh DRY against performance here. Normally it should not matter, though, because both variants do not take long.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download