添加一个回调函数来一个Ruby数组做一些事情的时候加一个元素 [英] Add a callback function to a Ruby array to do something when an element is added

查看:126
本文介绍了添加一个回调函数来一个Ruby数组做一些事情的时候加一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要像一个回调函数添加到一个Ruby数组,这样,当元素被添加到该数组,这个函数被调用。
有一件事我能想到的是覆盖所有的方法(如<&LT,=,插入,...)。并调用回调函数从那里

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 override all methods (like <<, =, insert, ...) and call that callback from there.

有没有更简单的解决方案?

Is there an easier solution?

推荐答案

在数组的大小发生了变化,这是下面的code只调用了 SIZE_CHANGED 挂钩通过数组的新大小:

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

这篇关于添加一个回调函数来一个Ruby数组做一些事情的时候加一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆