簡體   English   中英

如何在Ruby中編寫“if in”語句

[英]How to write an “if in” statement in Ruby

我正在尋找像Python這樣的if-in語句用於Ruby。

從本質上講,如果x an_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
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支持set操作。 如果你想簡潔/簡潔,你可以這樣做:

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

將其轉換為布爾值很容易:

!(%w[a b c d e f] & ['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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM