Friday, June 25, 2010

Modifying an Existing Ruby Class

First example is reopening the class and adding methods to it.


First, the original class:


class OriginalGangsta
   def shoot
      puts 'bang!' 
   end

   def flee
      puts 'run muther###'
   end
end


Now, we modify the class:


#load the original class
require 'original_gangsta'

#add some new methods
class OriginalGangsta
   def lie
      puts "he dunnit"
   end

   def dance
      puts "I'm a dancin' fool"
   end
end


We can also just modify an instance of the class:


og = OriginalGangsta.new

class << og
   def cry
      puts "I never had a good home!"
   end
end

or we can do it this way:

og = OriginalGangsta.new

def og.cry
   puts "I never had a good home!"
end

No comments: