Created
February 22, 2011 19:52
-
-
Save saoj/839245 to your computer and use it in GitHub Desktop.
This is an eigenclass (singleton class) annoying bug that was fixed in Ruby 1.9.2
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
| # Add method filter to array | |
| class Array | |
| def filter(str) | |
| self.sort.select do |m| | |
| m =~ /^#{str}/i | |
| end | |
| end | |
| end | |
| class A | |
| def m_a | |
| puts "inside m_a" | |
| end | |
| end | |
| class B < A | |
| def m_b | |
| puts "inside m_b" | |
| end | |
| end | |
| puts "Test 1:" | |
| p B.instance_methods.filter('m_') # both 'm_a' and 'm_b' are listed | |
| p B.instance_methods(false).filter('m_') # superclasses are ignored | |
| # only 'm_b' is listed | |
| # ok, now let's move to the eigenclass | |
| class Object | |
| def eigenclass | |
| class << self | |
| self | |
| end | |
| end | |
| end | |
| b1 = B.new | |
| def b1.m_only_from_b1 | |
| puts "only from b1" | |
| end | |
| puts "Test 2:" | |
| p A.instance_methods.filter('m_') # m_a is listed | |
| p B.instance_methods.filter('m_') # m_a and m_b are listed | |
| p B.instance_methods(false).filter('m_') # only m_b is listed | |
| puts "Test 3:" | |
| p b1.eigenclass.instance_methods.filter('m_') | |
| # THE RUBY 1.8.7 BUG: | |
| p b1.eigenclass.instance_methods(false).filter('m_') | |
| ## Ahaaaa! This was fixed in ruby 1.9.2. It was buggy on ruby 1.8.7 | |
| # In Ruby 1.8.7 the output was: ["m_b", "m_only_from_b1"], in other words, "m_b" was incorrectly returned | |
| # In Ruby 1.9.2 the output is now: ["m_only_from_b1"] which is what one would expect | |
| # Thanks for the Ruby team for correcting that annoying bug... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment