Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer into a signed string in Ruby

Tags:

integer

ruby

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?

like image 417
Tom Lehman Avatar asked Mar 05 '10 19:03

Tom Lehman


2 Answers

"%+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)
like image 78
Wayne Conrad Avatar answered Sep 30 '22 10:09

Wayne Conrad


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.

like image 22
Stefan Kendall Avatar answered Sep 30 '22 09:09

Stefan Kendall