Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an "if in" statement in Ruby

I'm looking for and if-in statement like Python has for Ruby.

Essentially, if x in an_array do

This is the code I was working on, where the variable "line" is an array.

def distance(destination, location, line)
  if destination and location in line
    puts "You have #{(n.index(destination) - n.index(location)).abs} stops to go"
  end
end
like image 880
Keith Johnson Avatar asked Mar 29 '13 21:03

Keith Johnson


1 Answers

if line.include?(destination) && line.include?(location)

if [destination,location].all?{ |o| line.include?(o) }

if ([destination,location] & line).length == 2

The first is the most clear, but least DRY.

The last is the least clear, but fastest when you have multiple items to check. (It is O(m+n) vs O(m*n).)

I'd personally use the middle one, unless speed was of paramount importance.

like image 55
Phrogz Avatar answered Oct 06 '22 01:10

Phrogz