Ruby, Ruby Tutorial

Ruby – How to create a Class and its Object

This post shows Ruby codes that create a simple class and objects from that class. Yes, Ruby is an old and weird programming language, but people and companies are still using it. Therefore, no one programming language has a monopoly on software development. We should always keep an open mind.

The Class Construct in Ruby

Creating a class in Ruby is straightforward if you’ve worked with other OOP languages such as Java before; this is just a review of some concepts. Consider the following codes that represent a class.

The line on top is a comment in Ruby. Anything line that starts with a pound (#) sign is a comment. Next, we have the keyword class and its name, Student. Moreover, the class definition ends at the end keyword.

The equivalent of this Ruby class in Java would be the following. In contrast to Ruby, Java uses curly places as part of a class definition.

Creating Objects from a class

Given the above Ruby class code, we will create an object of that class when we run the following codes.

In Java, the equivalent would be the following.

Notice how similar the two constructs are. However, Ruby is different from Java, and it is best not to assume behaviors in Ruby codes. This is true, especially when we come from another programming language.

For more information, please check out the Ruby documentation.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like