Ruby: Module, Mixins and Blocks confusing?

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

    In response to @zeronone "How can we avoid such namespace clashes?"

    Avoid monkeypatching core classes wherever possible is the first rule. A better way to do this (IMO) would be to subclass Array:

    class MyArray < Array
      include Inject 
      # or you could just dispense with the module and define this directly.
    end
    
    
    xs = MyArray.new([1, 2, 3, 4, 5])
    # => [1, 2, 3, 4, 5]
    xs.sum
    # => 15
    xs.product
    # => 120
    [1, 2, 3, 4, 5].product
    # => [[1], [2], [3], [4], [5]]
    

    Ruby may be an OO language, but because it is so dynamic sometimes (I find) subclassing gets forgotten as a useful way to do things, and hence there is an over reliance on the basic data structures of Array, Hash and String, which then leads to far too much re-opening of these classes.

提交回复
热议问题