添加一个回调函数到Ruby数组,以便在添加元素时执行某些操作

Zar*_*doz 2 ruby arrays callback

我想在Ruby数组中添加类似回调函数的东西,这样当元素添加到该数组时,就会调用此函数.我能想到的一件事是覆盖所有方法(如<<,=,insert,...)并从那里调用该回调.

有更简单的解决方案吗?

hor*_*guy 6

以下代码仅size_changed在数组大小更改时调用挂钩并传递数组的新大小:

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
Run Code Online (Sandbox Code Playgroud)