如何编写适用于所有数字的方法

lon*_*556 1 ruby inheritance class-method

我正在写一个Fixnum类方法to_words,它接受任何数字并将其翻译成英语,所以,

2.to_words
#=> "two"
2030.to_words
#=> "two thousand thirty" 
Run Code Online (Sandbox Code Playgroud)

我希望它能够处理所有数字,并且一旦我得到一点点超过10亿就会出现问题:

1000002000.to_words
#=> "one billion two thousand"
1074000000.to_words
#=> NoMethodError
1074000000.class
#=> Bignum
Run Code Online (Sandbox Code Playgroud)

有没有办法将我的Fixnum.to_words方法扩展到Bignum

ptd*_*ptd 5

无论FixnumBignum继承Integer,所以这将是你的情况最好确定#to_wordsInteger这样无论是FixnumS或Bignums就继承该方法.