Ruby: Module, Mixins and Blocks confusing?

前端 未结 5 672
忘了有多久
忘了有多久 2021-01-15 12:55

Following is the code I tried to run from the Ruby Programming Book http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html

Why doesn\'t the

5条回答
  •  长情又很酷
    2021-01-15 13:20

    Add this line at the end of your code :

    p Array.ancestors
    

    and you get (in Ruby 1.9.3) :

    [Array, Inject, Enumerable, Object, Kernel, BasicObject]
    

    Array is a subclass of Object and has a superclass pointer to Object. As Enumerable is mixed in (included) by Array, the superclass pointer of Array points to Enumerable, and from there to Object. When you include Inject, the superclass pointer of Array points to Inject, and from there to Enumerable. When you write

    [1, 2, 3, 4, 5].product

    the method search mechanism starts at the instance object [1, 2, 3, 4, 5], goes to its class Array, and finds product (new in 1.9) there. If you run the same code in Ruby 1.8, the method search mechanism starts at the instance object [1, 2, 3, 4, 5], goes to its class Array, does not find product, goes up the superclass chain, and finds product in Inject, and you get the result 120 as expected.

    You find a good explanation of Modules and Mixins with graphic pictures in the Pickaxe http://pragprog.com/book/ruby3/programming-ruby-1-9

    I knew I had seen that some are asking for a prepend method to include a module before, between the instance and its class, so that the search mechanism finds included methods before the ones of the class. I made a seach in SO with "[ruby]prepend module instead of include" and found among others this :

    Why does including this module not override a dynamically-generated method?

提交回复
热议问题