猴子修补范围有限

猴子修补的主要问题是它污染了全局范围。你的代码工作受到你使用的所有模块的支配,而不是踩到彼此的脚趾。Ruby 的解决方案是改进,基本上是有限范围内的猴子补丁。

module Patches
  refine Fixnum do
    def plus_one
      self + 1
    end

    def plus(num)
      self + num
    end

    def concat_one
      self.to_s + '1'
    end
  end
end

class RefinementTest
  # has access to our patches
  using Patches

  def initialize
    puts 1.plus_one
    puts 3.concat_one
  end
end

# Main scope doesn't have changes

1.plus_one
# => undefined method `plus_one' for 1:Fixnum (NoMethodError)

RefinementTest.new
# => 2
# => '31'