Keith Johnson
Keith Johnson

Reputation: 730

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

Upvotes: 5

Views: 2651

Answers (5)

Pavling
Pavling

Reputation: 3963

If it is that you want to ensure that both destination and location are in line, I'd go with one intersect in preference to two ".include?" checks:

def distance(destination, location, line)
  return if ([destination, location] - line).any? # when you subtract all of the stops from the two you want, if there are any left it would indicate that your two weren't in the original set
  puts "You have #{(line.index(destination) - line.index(location)).abs} stops to go"
end

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160551

Ruby supports set operations. If you want concise/terse, you can do:

%w[a b c d e f] & ['f']
=> ['f']

Turning that into a boolean is easy:

!(%w[a b c d e f] & ['f']).empty?
=> true

Upvotes: 0

Phrogz
Phrogz

Reputation: 303198

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.

Upvotes: 4

squiguy
squiguy

Reputation: 33370

How about using include?

def distance(destination, location, line)
  if line.any? { |x| [destination, location].include?(x) }
    puts "You have #{(n.index(destination) - n.index(location)).abs} stops to go"
  end
end

Upvotes: 2

tokland
tokland

Reputation: 67850

You can use Enumerable#include? -which looks a bit ugly- or create your own abstraction so you can write write how you think about the operation:

class Object
  def in?(enumerable)
    enumerable.include?(self)
  end
end


2.in?([1, 2, 3]) #=> true

Upvotes: 1

Related Questions