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

Image of Stellar post

How a Hackathon Project became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Watch the video

Top comments (0)

AWS Industries LIVE! Stream

Watch AWS Industries LIVE!

Watch Industries LIVE! to find out how the AWS cloud helps solve real-world business challenges.

Learn More

đź‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay