Ruby: Module, Mixins and Blocks confusing?

前端 未结 5 649
忘了有多久
忘了有多久 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:26

    By the way: in Ruby 2.0, there are two features which help you with both your problems.

    Module#prepend prepends a mixin to the inheritance chain, so that methods defined in the mixin override methods defined in the module/class it is being mixed into.

    Refinements allow lexically scoped monkeypatching.

    Here they are in action (you can get a current build of YARV 2.0 via RVM or ruby-build easily):

    module Sum
      def sum(initial=0)
        inject(initial, :+)
      end
    end
    
    module ArrayWithSum
      refine Array do
        prepend Sum
      end
    end
    
    class Foo
      using ArrayWithSum
    
      p [1, 2, 3].sum
      # 6
    end
    
    p [1, 2, 3].sum
    # NoMethodError: undefined method `sum' for [1, 2, 3]:Array
    
    using ArrayWithSum
    p [1, 2, 3].sum
    # 6
    

提交回复
热议问题