Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite a method dynamically

I want to overwrite method Hash#[]= dynamically by calling a method f. The following code doesn't work because class definition is not allowed inside a method:

def f
  class Hash
    def []=(k, v)
      ...
    end
  end
end

A workaround is to put class Hash in a separate file, then

def f
  require 'my_hash.rb'
end

I wonder if there is a way to avoid adding a separate file.

like image 503
TieDad Avatar asked Mar 14 '23 18:03

TieDad


2 Answers

def f
  Hash.send(:define_method, :[]=) do |x, y|
    ...
  end
end
like image 67
sawa Avatar answered Mar 27 '23 22:03

sawa


Here is another way to do it:

def f
    Hash.class_eval do
        def []=(k, v)
          #...
        end
    end
end
like image 44
Wand Maker Avatar answered Mar 27 '23 21:03

Wand Maker