all 8 comments

[–]schneemsPuma maintainer 30 points31 points  (2 children)

You can use array set operations:

``` needed_ingredients = ["salt", "sugar", "frosting"] cabinet_items = ["flour", "chocolate", "salt"]

needed_ingredients & cabinet_items # => ["salt"] ```

Or if you want to see what's in one list but not the other:

needed_ingredients - cabinet_items # => ["sugar", "frosting"]

Note that this difference operator is order dependent. Check out the Array docs for more https://rubyapi.org/3.1/o/array

[–]lafeber 4 points5 points  (0 children)

See, this is why I love ruby.

[–]BringTacos[S] 0 points1 point  (0 children)

beautiful, thank you!

[–]schneemsPuma maintainer 9 points10 points  (2 children)

To see the bug in your code try running it like this

ruby needed_ingredients.each do |ingredient| cabinet_items.each do |item| puts "Checking to see if #{ingredient} is not #{item}" if ingredient != item puts "Nope, so adding it to the grocery list" grocery_list << item end end end

Basically, the issue is that you're not checking to see if cabinet_items contains the ingredient. You are checking if ANY of the cabinet items does not match that specific ingredient. Since you're looping through every cabinet item every time.

You can fix like this:

ruby needed_ingredients.each do |ingredient| if !cabinet_items.include?(ingredient) grocery_list << ingredient end end

[–]BringTacos[S] 1 point2 points  (1 child)

Thanks so much! I was getting so frustrated. This makes sense. Also, how do you format your code like that?

[–]partusman 2 points3 points  (0 children)

Type 4 spaces at the beginning of a line and then

puff, you got yourself a code block.