What To Buy
Part of the Fundamentals section of Coddy's Ruby journey — lesson 88 of 88.
Challenge
EasyRead a shopping list and store inventory from input, then determine which items can be purchased.
You will receive:
- First line: comma-separated item names representing your shopping list
- Second line: the number of items in the store inventory
- 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,3The output should be:
apples - Yes
bread - No
milk - YesIf the inputs are:
eggs,butter,cheese,yogurt
2
eggs,12
cheese,0The output should be:
eggs - Yes
butter - No
cheese - No
yogurt - NoIf the inputs are:
water
1
water,100The output should be:
water - YesTry 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 itemAll lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False