Search code examples
arraysrubyinclude

Looking for a string and returning the first string that matches a set


Poor title...need to think on how to reword it. Here is what I have to do:

Create a find_the_cheese method that should accept an array of strings. It should then look through these strings to find and return the first string that is a type of cheese. The types of cheese that appear are "cheddar", "gouda", and "camembert".

For example:

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


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

If, sadly, a list of ingredients does not include cheese, return nil:

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

You can assume that all strings will be lowercase. Take a look at the .include method for a hint. This method asks you to return a string value instead of printing it so keep that in mind.

Here is my code :

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

The error I am getting looks like it is grabbing the first element in the array even though it's none of the cheeses...can someone explain what is going on here? Any help is much appreciated as always.

These are the tests that will run through it:

  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

Here is the error:

  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)>'

Solution

  • This expression

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

    always returns

    "cheddar"
    

    it's not what you want. You're probably looking for something like

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

    What you wanted to write was probably

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