Menu
Coddy logo textTech

What To Buy

Part of the Fundamentals section of Coddy's Ruby journey — lesson 88 of 88.

challenge icon

Challenge

Easy

Read a shopping list and store inventory from input, then determine which items can be purchased.

You will receive:

  1. First line: comma-separated item names representing your shopping list
  2. Second line: the number of items in the store inventory
  3. Following lines: each contains an item name and quantity separated by a comma

For example, the inventory input apples,5 means the store has 5 apples in stock.

For each item in your shopping list, print the item name followed by - Yes if it can be bought, or - No if it cannot.

An item can be bought if:

  • It exists in the store inventory AND
  • Its quantity is greater than 0

If an item is not in the inventory at all, or has a quantity of 0, print No.

For example, if the inputs are:

apples,bread,milk
3
apples,5
bread,0
milk,3

The output should be:

apples - Yes
bread - No
milk - Yes

If the inputs are:

eggs,butter,cheese,yogurt
2
eggs,12
cheese,0

The output should be:

eggs - Yes
butter - No
cheese - No
yogurt - No

If the inputs are:

water
1
water,100

The output should be:

water - Yes

Try it yourself

# Read the shopping list (comma-separated items)
shopping_list = gets.chomp.split(',')

# Read the number of inventory items
n = gets.to_i

# Read the store inventory
inventory = {}
n.times do
  line = gets.chomp.split(',')
  item_name = line[0]
  quantity = line[1].to_i
  inventory[item_name] = quantity
end

# TODO: Write your code below
# For each item in the shopping list, check if it can be bought
# An item can be bought if it exists in inventory AND has quantity > 0
# Print "item_name - Yes" or "item_name - No" for each item

All lessons in Fundamentals