【问题标题】:How to write an "if in" statement in Ruby如何在 Ruby 中编写“if in”语句
【发布时间】:2013-03-29 21:24:50
【问题描述】:

我正在寻找像 Python 对 Ruby 的 if-in 语句。

基本上,如果 x in 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

【问题讨论】:

  • "destination and location in line",意思是destination和location都必须在line?这也不是你用 python 写的方式。
  • 如“destinationlocation 都在 line”或“destination 为真,locationline”中?
  • 因为目标和位置都在一个名为 line 的数组中。

标签: ruby arrays if-statement


【解决方案1】:
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)。)

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

【讨论】:

  • 嗯,你的最后一种方法可能更快,所以 +1。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

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

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

      【讨论】:

        【解决方案5】:

        如果您想确保目的地和位置都在一条线上,我会选择一个相交而不是两个“.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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-28
          • 2021-10-13
          • 2010-10-29
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多