How to write an "if in" statement in Ruby

I am also looking for an if-in statement such as Python for Ruby.

Essentially, if x in an_array do

This is the code I worked on, where the variable "string" 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 
+4
source share
5 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 clearest, but least DRY.

The latter is the least understood, but the fastest, when you have several items to check. (This is O(m+n) vs O(m*n) .)

I would use medium if speed were not of primary importance.

+3
source

How about using enable?

 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 
+2
source

Can you use Enumerable # include? that looks a little ugly, or create your own abstraction so that you can write how you think about the operation:

 class Object def in?(enumerable) enumerable.include?(self) end end 2.in?([1, 2, 3]) #=> true 
0
source

Ruby supports installation operations. If you want a short / short, you can do:

 %w[abcdef] & ['f'] => ['f'] 

Including this in a boolean is easy:

 !(%w[abcdef] & ['f']).empty? => true 
0
source

If you want both destinations and places to be in line, I would go with one intersecting, preferably 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 
0
source

All Articles