Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does define_method override a method with the same name as its argument?

Tags:

ruby

I have come across the following code :

  class MethodLogger
    def log_method((klass,method_name)
      klass.class_eval do
        alias_method "#{method_name}_original" method_name
        define_method method_name do
          puts "#{Time.now}: Called #{method_name}"
          send "#{method_name}_original"
        end
      end
    end
  end


class Tweet
 def say_hi
  puts "Hi"
 end
end

logger =MethodLogger.new
logger.log_method(Tweet,:say_hi)

This gives output

2012-09-11 12:54:09 -400: Called say_hi

So, how does the define_method :say_hi override the original method :say_hi ? Or does define_method change the original method definition ?

like image 980
simha Avatar asked May 29 '13 10:05

simha


1 Answers

If you define a method multiple times, all latter definitions will simply overwrite the older ones. There can only be one method with the same name.

like image 107
Jörg W Mittag Avatar answered Nov 09 '22 03:11

Jörg W Mittag