开发者

Convert an integer into a signed string in Ruby

I have a report in w开发者_Go百科hich 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.


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

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜