如何在Ruby中编写“if in”语句

我正在寻找像Python这样的if-in语句用于Ruby。

基本上,如果an_array中的x

这是我正在处理的代码,其中变量“line”是一个数组。

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 

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

第一个是最明确但最不干燥的。

最后一个是最不清楚的,但是当您有多个要检查的项目时最快。 (它是O(m+n) vs O(m*n) 。)

我个人使用中间的,除非速度至关重要。

使用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 

你可以使用Enumerable #include? – 看起来有点难看 – 或创建自己的抽象,所以你可以写下你对操作的看法:

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

Ruby支持集合操作。 如果你想要简洁/简洁,你可以这样做:

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

将其转换为布尔值很容易:

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

如果你想确保目的地和位置都在一条直线上,我会选择一个交叉点而不是两个“.include?”。 检查:

 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