Ruby Class Examples
Below we will create a Ruby class named Customer and declare two methods:
- display_details: This method is used to display the customer's detailed information.
- total_no_of_customers: This method is used to display the total number of customers created in the system.
Examples
display_detailsThe method contains three puts statements, which display the customer ID, customer name, and customer address. Among them, the puts statements:
will display the text Customer id and the value of the variable @cust_id on a single line.
When you want to display the text and value of an instance variable on a single line, you need to place the symbol (#) before the variable name in the puts statement. The text and the instance variable with the symbol (#) should be enclosed in double quotes.
The second method, total_no_of_customers, contains the class variable @@no_of_customers. The 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 shown below:
Here, we create two objects of the Customer class, cust1 and cust2, and pass the necessary parameters to the new method. When the initialize method is called, the necessary attributes of the object are initialized.
Once the object is created, you need to use the two objects to call the class methods. If you want to call a method or any data member, you can write code as shown below:
The object name is always followed by a dot, and then the method name or data member. We have seen how to call the two methods using the cust1 object. Using the cust2 object, you can also call the two methods, as shown below:
Save and execute the code
Now, put all the source code in the main.rb file, as shown below:
Examples
Try it »
Then, run the program, as shown below:
$ ruby main.rb
This will produce the following result:
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: 2Other Extensions