Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
  end
end

can this be written like

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

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

like image 839
Biketire Avatar asked May 16 '13 10:05

Biketire


People also ask

What does == mean in Ruby?

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not. str1 = “This is string”

What does :: represent in Ruby?

The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.


1 Answers

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

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.

like image 108
undur_gongor Avatar answered Sep 20 '22 13:09

undur_gongor