我应该如何指定有理数在 Ruby 中以十进制表示法显示?
如果我决定在 Ruby 中使用有理数作为控制台应用程序,但不希望它们显示为分数,是否有一种惯用的方法来指定它们应该以十进制表示法显示?
我所知道的选项包括:
fraction = Rational(1, 2)
puts "Use to_f: #{fraction.to_f}"
puts(sprintf("Use sprintf %f", fraction))
class Rational
def to_s
to_f.to_s
end
end
puts "Monkey patch Rational#to_s: #{fraction}"
还有其他选择吗?
If I decide to use Rationals in Ruby for a console application, but don't want them displayed as a fraction, is there an idiomatic way to specify they should be displayed in decimal notation?
Options I know about include:
fraction = Rational(1, 2)
puts "Use to_f: #{fraction.to_f}"
puts(sprintf("Use sprintf %f", fraction))
class Rational
def to_s
to_f.to_s
end
end
puts "Monkey patch Rational#to_s: #{fraction}"
Are there any alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 sprintf 中使用
%g
来获得“正确”的精度:我个人会像您一样使用猴子补丁理性,但我是猴子补丁的粉丝。覆盖内置的 to_s 行为似乎完全适合控制台应用程序。
也许您还有另一种选择,您可以编写自己的控制台,定义
Object#to_console
来调用to_s
,然后您可以在自己的Rational#to_console< 中进行猴子修补。 /代码> 相反。这种额外的努力将使事情变得更安全,因为有 0.1% 的可能性,某些库已经以某种方式使用
Rational#to_s
,从而破坏了您的补丁。You can use
%g
in the sprintf to get the 'right' precision:I'd personally monkey patch rational as you have, but then I'm a fan of monkey patching. Overriding the built-in
to_s
behavior seems entirely appropriate for a console application.Perhaps you have another alternative where you write your own console that defines
Object#to_console
to callto_s
, and then you could monkey patch in your ownRational#to_console
instead. That extra effort would make it safer for the 0.1% chance that some library is usingRational#to_s
already in a way that will break with your patch.