【问题标题】:First array element that matches an element in another array与另一个数组中的元素匹配的第一个数组元素
【发布时间】:2015-12-19 18:29:09
【问题描述】:

我正在尝试返回给定数组中与预设数组中的元素匹配的第一个元素。我有这个:

def find_the_cheese(a)
  cheese_types = ["cheddar", "gouda", "camembert"]
  a.collect{|c| cheese_types.include?(c)}.include?(true)
end

但它返回 true 而不是括起来的括号中的 c 值。如何返回匹配的元素?

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    以下代码将返回包含在 cheese_types 中的食物元素

    def find_the_cheese(food)
      cheese_types = ["cheddar", "gouda", "camembert"]
      food & cheese_types
    end
    

    【讨论】:

      【解决方案2】:

      Array 类包括 Enumerable 模块。 Enumerable#find 就是这样做的:

      def find_the_cheese(foods)
        cheeses = ["cheddar", "gouda", "camembert"]
        foods.find { |food| cheeses.include?(food) }
      end
      

      【讨论】:

        【解决方案3】:
        CheeseTypes = ["cheddar", "gouda", "camembert"]
        def find_the_cheese(a)
          (a & CheeseTypes).first
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-23
          • 1970-01-01
          • 2017-02-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多