5

我正在寻找和 if-in 类似 Python 的 Ruby 语句。

本质上,如果 xan_array 做

这是我正在处理的代码,其中变量“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
4

5 回答 5

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

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

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

第一个是最清晰但最不干燥的。

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

我个人会使用中间那个,除非速度是最重要的。

于 2013-03-29T21:30:58.930 回答
2

如何使用包含?

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
于 2013-03-29T21:27:04.190 回答
1

你可以使用Enumerable#include? - 看起来有点难看 - 或者创建你自己的抽象,这样你就可以写出你对操作的看法:

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


2.in?([1, 2, 3]) #=> true
于 2013-03-29T21:30:52.790 回答
0

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

%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
于 2013-03-29T22:47:13.857 回答
0

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
于 2013-03-30T08:29:21.967 回答