Add a callback function to a Ruby array to do something when an element is added

后端 未结 3 1340
后悔当初
后悔当初 2021-02-04 22:21

I\'d like to add something like a callback function to a Ruby array, so that when elements are added to that array, this function is called. One thing I can think of is to overr

3条回答
  •  無奈伤痛
    2021-02-04 23:09

    The following code only invokes the size_changed hook when the array size has changed and it is passed the new size of the array:

    a = []
    
    class << a
      Array.instance_methods(false).each do |meth|
        old = instance_method(meth)
        define_method(meth) do |*args, &block|
          old_size = size
          old.bind(self).call(*args, &block)
          size_changed(size) if old_size != size
        end if meth != :size
      end
    end
    
    def a.size_changed(a)
      puts "size change to: #{a}"
    end
    
    a.push(:a) #=> size change to 1
    a.push(:b) #=> size change to 2
    a.length 
    a.sort!
    a.delete(:a) #=> size change to 1
    

提交回复
热议问题