在 Ruby 中将整数转换为有符号字符串
我有一份报告,其中列出了总值,然后在括号中列出了更改。例如:
歌曲:45(上周+10)
所以我想将整数10打印为“+10”,将-10打印为“-10”
现在我正在做
(song_change >= 0 ? '+' : '') + song_change.to_s
有没有更好的方式?
I have a report in which I'm listing total values and then changes in parentheses. E.g.:
Songs: 45 (+10 from last week)
So I want to print the integer 10 as "+10" and -10 as "-10"
Right now I'm doing
(song_change >= 0 ? '+' : '') + song_change.to_s
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
String#% 根据到字符串中的打印说明符。打印说明符“%d”表示十进制。整数,并且添加到打印说明符的“+”强制始终打印适当的符号。
您可以在 Kernel#sprintf 中找到有关打印说明符的更多信息,或者在 sprinf 手册页中。
您可以通过传入一个数组来一次格式化多个内容:
String#% formats the right-hand-side according to the print specifiers in the string. The print specifier "%d" means decimal aka. integer, and the "+" added to the print specifier forces the appropriate sign to always be printed.
You can find more about print specifiers in Kernel#sprintf, or in the man page for sprinf.
You can format more than one thing at once by passing in an array:
您可以向 Fixnum 添加一个名为 to_signed_s 的方法,但这可能有点过头了。不过,您可以消除复制和粘贴,这会很好。
就我个人而言,我只需编写一个 StringUtil 类来处理转换。
或者,更好的面向对象解决方案是将 FixNum 包装在holder类中并覆盖该类的to_s。
IE:创建一个名为 SignedFixnum 的类,并在需要签名时将 Fixnum 对象包装在其中。
You could add a method to Fixnum called to_signed_s, but that may be overkill. You would eliminate copying and pasting, however, which would be good.
Personall, I'd just write a StringUtil class to handle the conversion.
Alternatively, a better OO solution would be to wrap the FixNum in a holder class and override THAT class's to_s.
IE: Create a class called SignedFixnum and wrap your Fixnum objects in it whenever they need to be signed.
韦恩已经发布了我认为最好的选择,但这里还有另一个只是为了好玩......
Wayne already posted what I consider the best option, but here's another one just for fun...
我认为你的原始代码很好,只需将它提取到一个助手中,这样它就不会扰乱你的视图,并且你不必每次想使用它时都重复它。
将其放入 application_helper.rb 文件中,如下所示
I think your original code is good, just extract it out into a helper so it doesn't clutter up your views and you don't have to repeat it each time that you want to use it.
Put it in your application_helper.rb file like this