Created
May 27, 2013 03:08
-
-
Save winsonwq/5654996 to your computer and use it in GitHub Desktop.
add hook when array size changed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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