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.
def f
  Hash.send(:define_method, :[]=) do |x, y|
    ...
  end
end
                        Here is another way to do it:
def f
    Hash.class_eval do
        def []=(k, v)
          #...
        end
    end
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With