Skip to content

Instantly share code, notes, and snippets.

@winsonwq
Created May 27, 2013 03:08
Show Gist options
  • Save winsonwq/5654996 to your computer and use it in GitHub Desktop.
Save winsonwq/5654996 to your computer and use it in GitHub Desktop.
add hook when 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment