简体   繁体   English

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

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

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. 我想在Ruby数组中添加类似回调函数的东西,这样当元素添加到该数组时,就会调用此函数。 One thing I can think of is to override all methods (like <<, =, insert, ...) and call that callback from there. 我能想到的一件事是覆盖所有方法(如<<,=,insert,...)并从那里调用该回调。

Is there an easier solution? 有更简单的解决方案吗?

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: 以下代码仅在数组大小更改时调用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

You should probably create your own class that wraps array. 您应该创建自己的包装数组的类。 You don't want to override a core class with a callback like you are describing, not only does that make the code brittle but it becomes less expressive for future developers who may not be expecting Array to make a callback. 您不希望像您所描述的那样使用回调覆盖核心类,这不仅会使代码变得脆弱,而且对于可能不期望Array进行回调的未来开发人员来说也变得不那么具有表现力。

使用“Observer”模式通知您希望观察的数组大小的变化: Ruby Observer这使您不必重写向数组添加元素的所有方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM