Create Your Own Car Inventory App with Ruby - A Beginner's Guide

Create Your Own Car Inventory App with Ruby - A Beginner's Guide

·

11 min read

Introduction

Welcome to this tutorial, which is aimed at new Ruby developers who want to learn how to build a simple car inventory application using Ruby. This tutorial is part of a larger project: a real Car Inventory Management System that I recently completed for one of my clients. I'm excited to share a few portions of this real-world project to inspire and assist new Ruby developers in gaining a solid understanding of Ruby programming concepts.

In this tutorial, I will guide you through the process of building the Car Inventory Application step-by-step. Before we dive into coding, we will start by planning our application to have a clear understanding of what we are building and what steps we need to take to achieve our goal. We will then cover the code implementation of the application, including creating car inventory data, displaying car options, getting customer information, and saving car selection.

By the end of this tutorial, you will have learned how to build a simple Ruby application and have a good understanding of the basic programming concepts. I hope this tutorial will motivate you to continue learning and exploring the exciting world of Ruby development. Thank you for joining me on this journey, and let's get started.

Prerequisites

To follow this tutorial, you will need

  • A basic understanding of Ruby programming language syntax.

  • Visual Studio Editor(VsCode).

  • How to use the command line to run this application.

  • Basic knowledge of Git to commit the code in your GitHub account.

  • Ruby version 2.7 or above is installed on your computer.

Topics Covered

This tutorial covers the following topics:

  • Creating a hash to store car inventory data.

  • Writing functions to display car options, select a car, and get customer information.

  • Updating the inventory after a customer places an order.

  • Using loops to continue the application until the customer decides to exit.

Planning The Project Part

  1. Project Goal:

The goal of this project is to create a car inventory application that allows customers to select a car from the inventory, enter their personal information, and save their orders.

  1. Features:

The main features of the application are:

  • Display the car inventory with details (make, model, color, year, price, and available quantity).

  • Allow the customer to select a car from the inventory.

  • Request the customer's personal information (name, mobile number, and delivery address).

  • Save the customer's order and update the car inventory by decreasing the available quantity of the selected car.

  • Provide the customer with an estimated delivery date for their order.

  • Allow the customer to select another car or exit the application.

  1. User Flow:

The user flow for the application is as follows:

  • The customer launches the application and is presented with the car inventory options.

  • The customer selects a car from the inventory.

  • The application requests the customer's personal information.

  • The customer enters their personal information.

  • The application saves the customer's order and updates the car inventory.

  • The application provides the customer with an estimated delivery date for their order.

  • The application asks the customer if they want to select another car or exit the application.

  • If the customer wants to select another car, they repeat the process from step 2.

  • If the customer wants to exit the application, the application thanks the customer for using the application and terminates.

Now that we have clearly defined all the requirements for the application, we can proceed to the coding phase.

The Code Part

  1. Car Inventory Data

CAR_INVENTORY = {
  :bmw_3_series => {
    color: "black",
    year: 2022,
    price: 40000,
    available_qty: 10
  },
  :bmw_5_series => {
    color: "white",
    year: 2021,
    price: 50000,
    available_qty: 5
  },
  :bmw_x5 => {
    color: "red",
    year: 2020,
    price: 60000,
    available_qty: 2
  }
}

In this code, you can see that we define a hash called CAR_INVENTORY to store information about different cars. Each car is represented by a symbol and contains information about the car's color, year, price, and number of available cars.

The reason for using symbols to represent each car here is that symbols are lightweight and immutable objects that are commonly used as keys in hashes. Unlike strings, symbols are not created each time they are used, which can make them more efficient to use as keys

Another reason, if you notice here that I used the car models (BMW 3 Series, BMW 5 Series, and BMW X5), which are used as keys in the hash. Since we don't need to change the keys and want to use them as unique identifiers, symbols are a good choice here.

Using symbols as keys also makes the code easier to read, especially when using the each method to iterate over the inventory data. For example, in the display_car_options method, we can use car (a symbol) to represent each car model, making the code more readable as you can see in the (Displaying Car Option)code below:

  1. Displaying Car Options

def display_car_options
  puts "Please select a car make and model from the following options:"
  CAR_INVENTORY.each do |car, attributes|
    puts "- #{car}: #{attributes[:color]} #{attributes[:year]} - $#{attributes[:price]} - Available Qty: #{attributes[:available_qty]}"
  end
end

In the display_car_options method, we define a function that will be called to show the available cars in the inventory. The reason we define a function here is to separate this part of the code from the rest of the logic and to make the code easier to read and maintain.

We also use a loop (each method) to iterate over the CAR_INVENTORY hash and print out the details for each car, including the (car's make and model, color, year, price, and available quantity). By using a loop, we can avoid repeating the same code for each car in the inventory. Instead, we can iterate over the inventory data and use the data to dynamically generate the output.

  1. Selecting a Car

def select_car
  loop do
    display_car_options
    puts "Enter the car make and model you would like to select:"
    car_selection = gets.chomp.to_sym
    if CAR_INVENTORY.has_key?(car_selection)
      return car_selection
    else
      puts "Invalid car make and model. Please try again."
    end
  end
end

Here you can see we define a function called select_car It starts by creating an infinite loop with the "loop do" statement. This means that the code inside the loop will continue to run until a specific condition is met.

Inside the loop, the method calls another method called "display_car_options" which presumably displays a list of available cars to choose from.

The method then prompts the user to enter the make and model of the car they want to select by printing the message "Enter the car make and model you would like to select:" and reading in the user's input with "gets.chomp". The ".to_sym" method is then called on the input to convert it into a symbol.

Next, the method checks whether the "CAR_INVENTORY" hash has a key that matches the user's input using the ".has_key?" method. If it does, then the method returns the user's selection as a symbol with "return car_selection".

If the user's input does not match any keys in the "CAR_INVENTORY" hash, then the method prints the message "Invalid car make and model. Please try again." and continues with the loop. The user is prompted to enter their selection again until a valid selection is made.

So, in summary, this method repeatedly prompts the user to select a car from a list until a valid selection is made and then returns the user's selection as a symbol.

  1. Getting Customer Information:

def get_customer_information
  puts "Please enter your full name:"
  full_name = gets.chomp
  puts "Please enter your mobile number:"
  mobile_number = gets.chomp
  puts "Please enter your delivery address:"
  delivery_address = gets.chomp
  return { full_name: full_name, mobile_number: mobile_number, delivery_address: delivery_address }
end

We define a function called get_customer_information. This function is a block of code that can be called and executed multiple times within a program. In this case, the purpose of the function is to get some information from a customer.

The first line of the function uses puts to print a message to the console, asking the user to enter their full name. The chomp method is called on the result of the gets method. gets stands for "get string" and allows the user to input a string value from their keyboard. The chomp method removes any trailing newline characters from the string.

The same process is repeated for the user's mobile number and delivery address. Finally, a hash is created using curly braces and the return keyword is used to return the hash to the caller of the function.

A hash is a collection of key-value pairs, similar to a dictionary in Python. In this case, the keys in the hash are full_name, mobile_number, and delivery_address. The values for these keys are the values entered by the user for their full name, mobile number, and delivery address, respectively.

  1. Saving Car Selection and Customer Information:

def save_car_selection(car_selection, customer_information)
  CAR_INVENTORY[car_selection][:available_qty] -= 1
  puts "Thank you for selecting #{car_selection}. Your order has been saved."
  puts "Customer Information:"
  puts "- Full Name: #{customer_information[:full_name]}"
  puts "- Mobile Number: #{customer_information[:mobile_number]}"
  puts "- Delivery Address: #{customer_information[:delivery_address]}"
  puts "Estimated Delivery Date: #{Time.now + (60*60*24*7)}"
end

This code defines a method called save_car_selection that takes two arguments, car_selection and customer_information.

The first line of the method CAR_INVENTORY[car_selection][:available_qty] -= 1 decrements the available quantity of the car that the customer has selected in the inventory by 1.

The second line puts "Thank you for selecting #{car_selection}. Your order has been saved." prints a message thanking the customer for selecting the car and letting them know that their order has been saved.

The next few lines print out the customer's information, including their full name, mobile number, and delivery address using interpolation, which is a way to insert the values of variables or expressions into a string.

Finally, the last line puts "Estimated Delivery Date: #{Time.now + (60*60*24*7)}" prints out an estimated delivery date, which is calculated by adding one week (in seconds) to the current time (as represented by the Time.now method).

Overall, this code is meant to update the inventory of available cars, provide confirmation of the customer's selection, and provide the customer with an estimated delivery date.

  1. Running the Application:

def run_car_inventory_application
  loop do
    car_selection = select_car
    customer_information = get_customer_information
    save_car_selection(car_selection, customer_information)
    puts "Would you like to select another car? (y/n)"
    response = gets.chomp.downcase
    break if response == "n"
  end
  puts "Thank you for using the Car Inventory Application."
end

This code is defining a function called run_car_inventory_application. The function contains a loop that continues to execute until the user decides to exit. Within the loop, there are a few steps that are executed:

  1. car_selection = select_car: This line is calling a method called select_car which is presumably defined elsewhere in the code. It is storing the value returned by that method in a variable called car_selection.

  2. customer_information = get_customer_information: Similarly to the previous line, this line is calling a method called get_customer_information which is also presumably defined elsewhere in the code. It is storing the value returned by that method in a variable called customer_information.

  3. save_car_selection(car_selection, customer_information): This line is calling a method called save_car_selection and passing in the car_selection and customer_information variables as arguments. This method is presumably responsible for saving the user's car selection and customer information somewhere (e.g. a database).

  4. puts "Would you like to select another car? (y/n)": This line is printing out a message to the user asking if they want to select another car.

  5. response = gets.chomp.downcase: This line is waiting for the user to input a response (either "y" or "n") and storing that response in a variable called response. gets.chomp is a method that waits for the user to input a line of text and removes the newline character at the end of the line. downcase is a method that converts the response to lowercase, so that the code can handle the user typing "Y" or "N" instead of "y" or "n".

  6. break if response == "n": This line is checking if the user's response was "n". If it was, the break keyword is used to exit the loop and move on to the next line of code.

After the loop finishes executing (because the user entered "n" when prompted), the code prints out a message thanking the user for using the car inventory application.

How to run this application using a command line

  1. Open your Terminal.

  2. Cd to the directory where you saved your Car Inventory Application file using the ruby extension, For example, if the file name: is car_inventory.rb, Then type in your Terminal

ruby car_inventory.rb

Then press Enter.

You Can check the entire code here on my GitHub.

Conclusion

In this tutorial, we covered how to create a basic car inventory application in Ruby. We went over the necessary steps to create the application, including how to define a hash to store car information, create methods to display car options, get user input, and save their selection and information. We also went over how to create the main loop that runs the application until the user decides to exit. This tutorial is intended for newbie Ruby developers with some knowledge of the command line and basic Git usage.

Remember, this is just a basic example of what you can do with Ruby. There are many ways to improve this application, such as adding error handling, improving the user interface, or even creating a web application using a framework like Ruby on Rails. Good luck with your future Ruby projects.