Convert an integer into a signed string in Ruby
integer, ruby
Solution
"%+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)
Problem
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?