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.
1 2 3 4 5 | # Student.rb class Student end |
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.
1 2 3 | public class Student { } |
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.
1 | mike = Student.new |
In Java, the equivalent would be the following.
1 | Student mike = new Student(); |
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.