Ruby Open Classes
In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever's there.
Now to the program p031motorcycletest.rb in the last topic, add the method dispAttr
require_relative 'p030motorcycle'
m = MotorCycle.new('Yamaha', 'red')
m.start_engine
class MotorCycle
def disp_attr
puts 'Color of MotorCycle is ' + @color
puts 'Make of MotorCycle is ' + @make
end
end
m.disp_attr
m.start_engine
puts self.class
puts self
Please note that self.class refers to Object and self refers to an object called main of class Object.
One more example is program - p031xdognext.rb
require_relative 'p029dog'
# define class Dog
class Dog
def big_bark
puts 'Woof! Woof!'
end
end
# make an object
d = Dog.new('Labrador', 'Benzy')
d.bark
d.big_bark
d.display
Here's another example of adding a method to the String class.
We would like to add a write_size method to the String class. But first, we shall get a list of all methods in Ruby's standard String class that begins with wr:
String.methods.grep /^wr/ # []
We observe that the String class has no method starting with wr. Now let's write the program p032mystring.rb:
class String
def write_size
self.size
end
end
size_writer = "Tell me my size!"
puts size_writer.write_size
(You can confirm the output to the above programs yourself).
If you're writing a new method that conceptually belongs in the original class, you can reopen the class and append your method to the class definition. You should only do this if your method is generally useful, and you're sure it won't conflict with a method defined by some library you include in the future.
If your method isn't generally useful, or you don't want to take the risk of modifying a class after its initial creation, create a subclass of the original class. The subclass can override its parent's methods, or add new ones. This is safer because the original class, and any code that depended on it, is unaffected.
Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.github.io and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.