Figure 7 at the command prompt.
Notice that as you type in your code, the interpreter is helping to format your code and as you enter your last "end" statement, Ruby returns => nil which is an indication that the Ruby interpreter has detected the end of your Rectangle class. Rectangle is now defined in this irb session.
Now try to create a few instances of your new Rectangle class. On the very next line, enter Rectangle.new(4,5) and then Rectangle.new(5,12). You should see Ruby again respond with new instances of your Rectangle:
Now let's try that area method. On the next irb command prompt line enter Rectangle.new(6,5).area(). You should see results that look like the following:
=> #<Rectangle:0x58d2ee8 @width=5, @height=4>
=> #<Rectangle:0x58cfdc8 @width=12, @height=5>
Cool?! Yes, and extremely powerful as you slowly build and test chunks of your application classes and methods. But wait, there is more.
In Ruby, classes are never closed. This means you can always add or redefine methods to an existing class. Say, for example, that you also wanted to add a circumference method to the Rectangle class that you created. On the command prompt, enter the following code a line at a time:
def circumference ()
@height * 2 + @width * 2
|Figure 7. Enter the Rectangle Class: Enter the definition of the Rectangle class into the fxri interactive Ruby interpreter as shown in the lower right-hand frame of this example.|
Has the Rectangle class just been defined again? No, the Ruby interpreter understands that you are making a modification to the current Rectangle class and it is adding a new method to the existing Rectangle class. Now enter the following line at the command prompt: Rectangle.new(2,3).circumference(). You should see results that look similar to those below:
To redefine any method already in the Rectangle class, for example the area method, simply reenter the class definition with the new area method definition:
irb(main):014:0> class Rectangle
irb(main):015:1> def circumference()
irb(main):016:2> @height * 2 + @width * 2
In the simple example above, the area method has been redefined to always return twice the height.
irb(main):020:0> class Rectangle
irb(main):021:1> def area()
The idea that a class is never closed applies to classes you define as well as those built into the language. For example's sake, let's add an area method to the String class. Enter the following code at the command prompt:
In this case, you are defining the "area" of a string to return the length of the string. Now, try this new method on your name as a String as shown with im below:
As you read this article, use the interactive nature of Ruby and its development environment to test and explore the programming language with the small chunks of Ruby code provided to you.
irb(main):026:0> class String
irb(main):027:1> def area()