DEV Community

brylenelavelle
brylenelavelle

Posted on

Ruby: Building a Grocery List Program Using Arrays and Hashes

def create_list
  # Prompts input from user
  print "What is the list name? "
  # Returns as value input to hash with key "name"
  name = gets.chomp
  # Creates hash assigned to variable hash
  # Variable "items" creates an array
  hash = { "name" => name, "items" => Array.new }
  return hash
end

def add_list_item
  # Prompts input from user
  print "What is the item called? "
  # Returns as value input to hash with key "item_name"
  item_name = gets.chomp

  print "How much? "
  # Returns as value input to hash with key "quantity"
  quantity = gets.chomp.to_i

  hash = { "name" => item_name, "quantity" => quantity }
  return hash
end

def print_separator(character= "-")
  puts character * 80
end

# To fancify the format of the printed list
def print_list(list)
  puts "List: #{list['name']}"
  print_separator()

  list["items"].each do |item|
    puts "\tItem: " + item['name'] + "\t\t\t" +
      "Quantity: " + item['quantity'].to_s
  end

  print_separator()
end

# Prints create_list
list = create_list()

puts "Great! Add some items to your list."
# Combines add_list_item hash to the 
# "items" array from create_list
# The three method calls also allows user to
# add items 3 times
list['items'].push(add_list_item())
list['items'].push(add_list_item())
list['items'].push(add_list_item())

puts "Here's your list:\n"
print_list(list)
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)