猴子在不重复的情况下修补 Fixnum 和 Bignum

Monkey patching Fixnum and Bignum without duplication

我已经添加了两个处理数字的小助手,但我发现我必须复制粘贴我的方法才能使其同时适用于 BignumFixnum。如何在没有这种复制粘贴的情况下为数字 类 编写方法?

class Bignum
    def digits
        self.to_s.split('').map(&:to_i)
    end

    def palindrome?
        self.to_s == self.to_s.reverse
    end
end

class Fixnum
    def digits
        self.to_s.split('').map(&:to_i)
    end

    def palindrome?
        self.to_s == self.to_s.reverse
    end
end

两个 class 都继承自 Integer。 Monkeypatch,如果你想影响两者。来自文档:

Integer

This class is the basis for the two concrete classes that hold whole numbers, Bignum and Fixnum.

2.0.0-p353 :001 > class Integer; def worked?; true; end; end
#=> nil 
2.0.0-p353 :002 > 42.worked?
#=> true 
2.0.0-p353 :003 > 42.class
#=> Fixnum 
2.0.0-p353 :004 > big = 2**90
#=> 1237940039285380274899124224 
2.0.0-p353 :005 > big.worked?
#=> true 
2.0.0-p353 :006 > big.class
#=> Bignum 

你可以找到共同的 classes 和模块使用集合交集:

Fixnum.ancestors & Bignum.ancestors
#=> [Integer, Numeric, Comparable, Object, Kernel, BasicObject] 

如果两个 classes(或更多)不共享适当的公共模块或 class,您可以选择这样做:

module MyExtension
  def palindrome?
    ...
  end
end

class NumbaOne
  include MyExtension
end

class NumbaTwo
  include MyExtension
end

或者,如果您不想修改整个 class,而只想修改某些实例:

a1 = NumbaOne.new
a2 = NumbaOne.new
b1 = NumbaTwo.new

[a1,a2,b1].each{ |o| o.extend MyExtension }