Forum: Ruby-core Multiple prepend modules

Posted by Guoliang Cao (gcao)
on 2013-03-08 05:28
Hello,

I did some quick experiment with prepend and noticed a strange behavior.

"prepend B; prepend C" and "prepend B, C" produce same ancestors.
However, their behaviors are different. IMHO, the second case is just a
shortcut of the first and they should be equivalent. Can someone please
explain why they behave differently?

Thanks,
Guoliang Cao

Please see the complete code and output below.

module B
  def test
    puts 'before B'
    super
    puts 'after B'
  end
end

module C
  def test
    puts 'before C'
    super
    puts 'after C'
  end
end

class A
  prepend B
  prepend C

  def test
    puts 'A'
  end
end

class AA
  prepend B, C

  def test
    puts 'AA'
  end
end

puts "prepend B; prepend C   => #{A.ancestors}\n\n"
A.new.test

puts "\n\nprepend B, C    => #{A.ancestors}\n\n"
AA.new.test

__END__
prepend B; prepend C   => [C, B, A, Object, Kernel, BasicObject]

before C
before B
A
after B
after C


prepend B, C    => [C, B, A, Object, Kernel, BasicObject]

before B
before C
AA
after C
after B
Posted by Guoliang Cao (gcao)
on 2013-03-08 21:39
My bad. There was a typo. The second A.ancestors should be AA.ancestors. 
Then all is fine.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.