Featured image of post Ruby Mini Project: Simple Menu Console App

Ruby Mini Project: Simple Menu Console App

Learn how to separate files on Ruby app

What we learn

  • Manage separate files of Ruby
  • Class Overriding
  • Class Inheritance
  • Initialize Method
  • Variable Instance

We will create a console app like this

console menu app

Project Structure

This is a small console app for ordering menu. Let create several ruby files within a folder called menu_app

1
2
3
4
5
menu_app
 |- index.rb
 |- menu.rb
 |- food.rb
 └- drink.rb

Creating files

Main File index.rb

In index.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require "./food"
require "./drink"

puts "All items are on sale on Sundays!"

food1 = Food.new(name: "Pizza", price: 8, calorie: 700)
food2 = Food.new(name: "Sushi", price: 10, calorie: 600)
drink1 = Drink.new(name: "Cola", price: 3, volume: 500)
drink2 = Drink.new(name: "Tea", price: 2, volume: 400)

menus = [food1, food2, drink1, drink2]

index = 0
menus.each do |menu|
  puts "#{index}. #{menu.info}"
  index += 1
end

puts "--------------"
puts "Select an item by its number:"
order = gets.chomp.to_i

selected_menu = menus[order]
puts "You have selected: #{selected_menu.name}"

puts "How many?(Buy 3 or more for $1 discount):"
count = gets.chomp.to_i

puts "The total price is $#{selected_menu.get_total_price(count)}"

Parent Class menu.rb

We put parent class in the file menu.rb with these following lines

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require "date"

class Menu
  attr_accessor :name
  attr_accessor :price
  
  def initialize(name:, price:)
    self.name = name
    self.price = price
  end
  
  def info
    return "#{self.name} $#{self.price}"
  end
  
  def get_total_price(count)
    total_price = self.price * count
    if count >= 3
      total_price -= 1
    end
    
    # Add an if statement
    if Menu.discount_day? && count >= 1
      total_price -= 1
    end
    
    return total_price
  end
  
  def Menu.discount_day?
    today = Date.today
    return today.sunday?
  end
end

Child Class food.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
  require "./menu"

class Food < Menu
  attr_accessor :calorie
  
  def initialize(name:, price:, calorie:)
    super(name: name, price: price)
    self.calorie = calorie
  end
  
  def info
    return "#{self.name} $#{self.price} (#{self.calorie}kcal)"
  end
  
  def calorie_info
    return "#{self.name} is #{self.calorie}kcal"
  end
end

Child Class drink.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
require "./menu"

class Drink < Menu
  attr_accessor :volume
  
  def initialize(name:, price:, volume:)
    super(name: name, price: price)
    self.volume = volume
  end
  
  def info
    return "#{self.name} $#{self.price} (#{self.volume}mL)"
  end
end
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy