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?
"%+d" % song_change
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:
song_count = 45
song_change = 10
puts "Songs: %d (%+d from last week)" % [song_count, song_change]
# => Songs: 45 (+10 from last week)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With