Ruby Class Case
The following will create a Ruby class called Customer that declares two methods:
- display_details: This method is used to display the details of the customer.
- total_no_of_customers: This method is used to display the total number of customers created in the system.
display_details method contains three puts statements that display the customer ID, customer name, and customer address. Where the puts statement:
The value of the text Customer id and the variable @cust_id will be displayed on a single line.
When you want to display the text and values of an instance variable on a single line, you need to place the symbol (#) in front of the variable name of the puts statement. Text and instance variables with a symbol (#) should be enclosed in double quotes.
The second method, total_no_of_customers, contains the class variable @@no_of_customers. Expression @@no_of_ Customers+=1 increments the variable no_of_customers by 1 each time the method total_no_of_customers is called. In this way, you will get the total number of customers in the class variable.
Now create two customers as follows:
Here, we created two objects of the Customer class, cust1 and cust2, and passed the necessary parameters to the new method. When the initialize method is called, the necessary properties of the object are initialized.
Once an object is created, you need to use two objects to call the methods of the class. If you want to call a method or any data member, you can write the code as follows:
The object name is always followed by a dot, followed by the method name or data member. We have seen how to call two methods using the cust1 object. With the cust2 object, you can also call two methods as follows:
Save and execute code
Now, put all the source code in the main.rb file as follows:
Next, run the program as follows:
$ ruby main.rb
This will produce the following results:
Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Total number of customers: 1 Customer id 2 Customer name Poul Customer address New Empire road, Khandala Total number of customers: 2