tags:

views:

75

answers:

4

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?

+1  A: 

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.

Stefan Kendall
I like the idea of a new class. Maybe that seems like overkill, but for all we know there could be a bunch of other functionality that could go in there. Or maybe there isn't yet but there will be later.
Shadowfirebird
This is pretty straightforward Decorator pattern, I think. For small projects it's overkill, but if this is to be reused much, it could net big gains.
Stefan Kendall
+15  A: 
"%+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)
Wayne Conrad
A: 

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

  def display_song_change
    (song_change >= 0 ? '+' : '') + song_change.to_s
  end
imightbeinatree at Cloudspace
+2  A: 

Wayne already posted what I consider the best option, but here's another one just for fun...

"#{'+' if song_change >= 0}#{song_change}"
Michael Kohl