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

How to write a method that works for all numbers

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

2.to_words
#=> "two"
2030.to_words
#=> "two thousand thirty" 

我希望它能处理所有数字,但一旦超过 10 亿就会出现问题:

1000002000.to_words
#=> "one billion two thousand"
1074000000.to_words
#=> NoMethodError
1074000000.class
#=> Bignum

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

FixnumBignum 都继承自 Integer,因此在您的情况下,最好在 Integer 上定义 #to_words,因此 Fixnums 或 Bignums 将继承该方法。