Ruby 2 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
  1. require_relative 'p030motorcycle'  
  2. m = MotorCycle.new('Yamaha''red')  
  3. m.start_engine  
  4.   
  5. class MotorCycle  
  6.   def disp_attr  
  7.     puts 'Color of MotorCycle is ' + @color  
  8.     puts 'Make  of MotorCycle is ' + @make  
  9.   end  
  10. end  
  11. m.disp_attr  
  12. m.start_engine  
  13. puts self.class  
  14. 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
  1. require_relative 'p029dog'  
  2. # define class Dog  
  3. class Dog  
  4.   def big_bark  
  5.     puts 'Woof! Woof!'  
  6.   end  
  7. end  
  8. # make an object  
  9. d = Dog.new('Labrador''Benzy')  
  10. d.bark  
  11. d.big_bark  
  12. 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:
  1. String.methods.grep /^wr/ # []  
We observe that the String class has no method starting with wr. Now let's write the program p032mystring.rb:
  1. class String  
  2.   def write_size  
  3.     self.size  
  4.   end  
  5. end  
  6. size_writer = "Tell me my size!"  
  7. 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.