Introduction to Ruby
Finally, we can put this all together in defining a class and some methods. We can create a class in irb, or anywhere else in Ruby, simply by saying:
class Simple end
Sure enough, we've managed to create a class in only two lines. Is this enough to create an object of type Simple? Let's see:
foo = Simple.new foo.class
It would seem so; our variable foo claims that it is of class Simple. We didn't specify what object Simple inherits from, so it automatically inherits from Object, the ultimate Ruby superclass. Ruby supports only single inheritance, which is stated in the class definition as:
class SimpleArray < Array end
We already have defined two classes, which is nice, but we haven't defined any methods specific to those classes. Ruby allows us to open up a class at any time, adding or replacing methods in a class. We define a method with the def statement, indicating whether the method takes any parameters, for example:
class Simple def id_squared return self.object_id * self.object_id end end
The method we have defined is quite simple, and it does something that I don't expect we would ever want to do—namely, it takes the object's unique ID (available via the inherited method object_id) and returns its doubled value (which will likely be an instance of Bignum).
If we type the above definition into irb, something amazing happens: our foo variable of class Simple now responds to the method Simple#id_squared! Yes, Ruby allows us to modify methods on the fly and to open up existing classes. We could, for example, modify the built-in Array or String classes, replacing the built-in methods with some of our own.
Finally, we might want to store some state in our object. This is done via instance variables. In Ruby, instance variables are preceded with the @ character, which might be a bit confusing if you are coming from the Perl world:
class Simple def initialize @simple_data = [ ] end end
The special initialize method is invoked whenever we create a new instance of Simple. So if we once again define foo to be an instance of Simple:
foo = Simple.new
we can see that foo now has an instance variable defined, by invoking:
The above returns an array:
How can we assign to @simple_data? And how can we retrieve its value? One way is to define a number of methods: one for writing this instance variable and one for retrieving its value. But a shorthand way would be to use the attr_reader and attr_writer methods:
class Simple attr_reader :simple_data attr_writer :simple_data end
The above code tells Ruby we have an instance variable named @simple_data, and that we would like to have methods created that will allow us to read and set its value. You can see here how symbols allow us to refer to an instance variable by something that is not a string, but not the literal variable either. With this in place, we can do things like:
foo = Simple.new foo.simple_data = 'abc' foo.simple_data = [1, 2, 3] print foo.simple_data.join(', ')
Ruby has become extremely popular in the last year or two, in no small part because of the growth of Ruby on Rails among Web developers. Even without Rails though, Ruby deserves much of the attention it has received. The fact that all data is stored in objects, the compactness and elegance of the method and block structures, and the very large number of objects included in the standard library all make for an impressive language.
This article didn't have space to go into some additional features that will be of interest to many Ruby programmers, such as modules, class variables, input/output with files, networking, XML parsing, the RubyGems library available on the Internet and built-in support for regular expressions. Ruby is a rich language, but it is fairly consistent and easy to learn—assuming you already have some background with object-oriented programming, which I think is the greatest hurdle to understanding Ruby.
Ruby still has a number of issues to resolve, including its relatively slow speed and a lack of Unicode support, but these are being addressed for future versions, and the community is one of the strongest that I've seen.
I have been using Ruby more and more during the last year and have grown to be quite impressed with the language. I suggest that you give Ruby a whirl as well. Even if you don't make it your primary programming language, it will get you thinking in new ways, and it might make programming in other languages more enjoyable too.
Resources for this article: /article/9017.
Reuven M. Lerner, a longtime Web/database consultant, is currently a PhD student in Learning Sciences at Northwestern University in Evanston, Illinois. He and his wife recently celebrated the birth of their son Amotz David.
Webinar: 8 Signs You’re Beyond Cron
11am CDT, April 29th
Join Linux Journal and Pat Cameron, Director of Automation Technology at HelpSystems, as they discuss the eight primary advantages of moving beyond cron job scheduling. In this webinar, you’ll learn about integrating cron with an enterprise scheduler.Join us!
|Android Candy: Intercoms||Apr 23, 2015|
|"No Reboot" Kernel Patching - And Why You Should Care||Apr 22, 2015|
|Return of the Mac||Apr 20, 2015|
|DevOps: Better Than the Sum of Its Parts||Apr 20, 2015|
|Play for Me, Jarvis||Apr 16, 2015|
|Drupageddon: SQL Injection, Database Abstraction and Hundreds of Thousands of Web Sites||Apr 15, 2015|
- Tips for Optimizing Linux Memory Usage
- "No Reboot" Kernel Patching - And Why You Should Care
- DevOps: Better Than the Sum of Its Parts
- Return of the Mac
- Android Candy: Intercoms
- Drupageddon: SQL Injection, Database Abstraction and Hundreds of Thousands of Web Sites
- Non-Linux FOSS: .NET?
- Play for Me, Jarvis
- Designing Foils with XFLR5