【问题标题】:Looking for a string and returning the first string that matches a set查找字符串并返回与集合匹配的第一个字符串
【发布时间】:2019-11-13 00:38:48
【问题描述】:

糟糕的标题...需要考虑如何改写它。这是我必须做的:

创建一个接受字符串数组的 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)>'

【问题讨论】:

    标签: arrays ruby include


    【解决方案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" }
    

    【讨论】:

    • 谢谢!啊,这么近。您的代码比我尝试做的要好,所以这是书籍中的代码。
    猜你喜欢
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2019-11-30
    • 2019-09-03
    • 2017-01-26
    相关资源
    最近更新 更多