Rubys magic language

This is a piece of code I keep to remind me of the magic in Ruby.

class Main
  # you can dynamically define methods with define_method
  # use {} or do/end
  define_method(:test2) { 
    puts "this is test2"
    test3 
  }

  def add_new_method
     # you can also send the :define_method to the class (note: self.class) 
     self.class.send(:define_method, :newMethod) do 
       test1 
       test2 
     end 
  end 

  def test1 
    puts "this is test1" 
  end 

  def test3 
    puts "this is test3" 
  end 
end 

class Doctor
  #dynamically define multiple methods 
  ["rhinoplasty", "checkup", "interpretive_dance"].each do |action| 
    define_method("perform_#{action}") do |argument| 
      "performing #{action.gsub('_', ' ')} on #{argument}" 
    end 
  end 
end

#
# Testing usage
# 
doctor = Doctor.new 
puts doctor.perform_rhinoplasty("nose") 
puts doctor.perform_checkup("throat") 
puts doctor.perform_interpretive_dance("in da club") 
m = Main.new 
m.test1 
m.test2 
m.add_new_method 
m.newMethod

Dynamically adding methods to your class can be very useful when creating DSLs or devtools that can be hard/impossible to create in other languages.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.