#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'csv'
# CSVファイルから商品リストを読み込み(Hash: { "商品名" => 単価 })
items = {}
CSV.foreach("items.csv", headers: true) do |row|
items[row["name"]] = row["price"].to_i
end
cart = []
total = 0
puts "=== 買い物プログラム (CSV版) ==="
puts "商品リスト:"
items.each { |name, price| puts " #{name} : #{price}円" }
puts "買いたい商品を入力してください(endで終了)"
loop do
print "商品名: "
name = gets&.strip
break if name.nil? || name.downcase == "end"
if items.key?(name)
print "数量: "
qty = Integer(gets&.strip || "0", exception: false) || 0
if qty <= 0
puts "数量は1以上で入力してください。"
next
end
price = items[name]
subtotal = price * qty
cart << { name: name, price: price, quantity: qty, subtotal: subtotal }
total += subtotal
puts "#{name} × #{qty} = #{subtotal}円 を追加しました。"
puts "現在の合計: #{total} 円"
puts "--------------------------"
else
puts "その商品はリストにありません。"
end
end
puts "\n=== お会計 ==="
cart.each do |item|
puts "#{item[:name]} (#{item[:price]}円 × #{item[:quantity]}個) = #{item[:subtotal]}円"
end
puts "合計金額: #{total} 円"