寻找一个字符串并返回与集合匹配的第一个字符串

时间:2019-07-02 11:13:23

标签: arrays ruby include

标题不佳...需要考虑如何重新命名。这是我要做的:

创建一个find_the_cheese方法,该方法应接受字符串数组。然后,它应浏览这些字符串以查找并返回第一种是奶酪类型的字符串。出现的奶酪类型为“切达干酪”,“古达干酪”和“卡门培尔奶酪”。

例如:

snacks = ["crackers", "gouda", "thyme"]
find_the_cheese(snacks)
#=> "gouda"


soup = ["tomato soup", "cheddar", "oyster crackers", "gouda"]
find_the_cheese(soup)
#=> "cheddar"

可悲的是,如果成分清单中不包含奶酪,则返回nil:

ingredients = ["garlic", "rosemary", "bread"]
find_the_cheese(ingredients)
#=> nil

您可以假定所有字符串均为小写。查看.include方法以获取提示。此方法要求您返回一个字符串值而不是打印它,因此请记住这一点。

这是我的代码:

def find_the_cheese(array)
  cheese_types = ["cheddar", "gouda", "camembert"]
  p array.find {|a| a == "cheddar" || "gouda" || "camembert"}
end

我得到的错误看起来像是抓住了数组中的第一个元素,即使不是奶酪……有人可以解释这里发生了什么吗?一如既往地感谢您的帮助。

这些将通过它进行测试:

  describe "#find_the_cheese" do
    it "returns the first element of the array that is cheese" do
      contains_cheddar = ["banana", "cheddar", "sock"]
      expect(find_the_cheese(contains_cheddar)).to eq 'cheddar'

      contains_gouda = ["potato", "gouda", "camembert"]
      expect(find_the_cheese(contains_gouda)).to eq 'gouda'
    end

    it "returns nil if the array does not contain a type of cheese" do
      no_cheese = ["ham", "cellphone", "computer"]
      expect(find_the_cheese(no_cheese)).to eq nil
    end
  end
end

这是错误:

  1) Cartoon Collections #find_the_cheese returns the first element of the array that is cheese
     Failure/Error: expect(find_the_cheese(contains_cheddar)).to eq 'cheddar'

       expected: "cheddar"
            got: "banana"

       (compared using ==)
     # ./spec/cartoon_collections_spec.rb:57:in `block (3 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:1)

此表达式

"cheddar" || "gouda" || "camembert"

总是返回

"cheddar"

这不是您想要的。您可能正在寻找类似的东西

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

您想写的可能是

array.find { |a| a == "cheddar" || a == "gouda" || a == "camembert" }