【发布时间】: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)>'
【问题讨论】: