红宝石有什么办法把浮子变成零碎的文字吗?
使:
fraction_to_words(1/3r)
=> "one third"
fraction_to_words(5/7r)
=> "five sevenths"
fraction_to_words(2/5r)
=> "two fifths"发布于 2020-12-17 11:09:57
您的问题与将任何数字转换为字符串相同。将浮点数转换为rational很容易(尽管可能会产生奇怪的结果,取决于浮点恶作剧)。你的问题是下一步--没有内置的--把数字转换成文字。如果你自己做事情,这可能会持续很长时间:
x = 0.75.to_r
denoms = ['unused', 'whole', 'half', 'third', 'quarter', 'fifth']
numerator = ['zero', 'one', 'two', 'three', 'four', 'five']
rational_name = numerator[x.numerator].to_s() + " " +denoms[x.denominator].to_s
if x.numerator > 1
rational_name += 's'
end你必须自己做大量的工作,或者找到一些已经有人把整数转换成单词的东西,比如在Using Ruby convert numbers to words?中。显然也有一个模块可以这样做:https://github.com/radar/humanize
您仍然需要为“特殊”分母(2 ->一半,3->第三……等等)提供自己的单词,并添加'th‘(2 11ths)等.
例如,使用该人性化库(从未使用过它,因此我不能评论它有多健壮):
rational_name = x.numerator.humanize..to_s() + " "
if x.denominator < 6
rational_name += denoms[x.denominator].to_s()
else
rational_name += x.denominator.humanize + 'th'
end
if x.numerator > 1
rational_name += 's'
end例如,我错过了这里的一半。(现在的“半场”是1.5)。不管怎样,这是一种开始的方式。
https://stackoverflow.com/questions/65339261
复制相似问题