Convert integer to signed string in Ruby

I have a report in which I list the common values ​​and then the changes in parentheses. For instance:.

Songs: 45 (+10 from last week)

So, I want to print the integer 10 as "+10" and -10 as "-10"

I'm doing now

(song_change >= 0 ? '+' : '') + song_change.to_s

Is there a better way?

+5
source share
4 answers
"%+d" % song_change

Line #% formats the right side according to the print specifiers in the line. The print specifier "% d" means decimal aka. an integer, and "+" added to the print specifier forcibly displays the corresponding character.

Kernel # sprintf sprinf.

, :

song_count = 45
song_change = 10
puts "Songs: %d (%+d from last week)" % [song_count, song_change]
# => Songs: 45 (+10 from last week)
+25

Fixnum, to_signed_s, . , .

StringUtil .

OO FixNum THAT to_s.

IE: SignedFixnum Fixnum, .

+1

, , ...

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

, , , , , .

Put it in the application_helper.rb file like this

  def display_song_change
    (song_change >= 0 ? '+' : '') + song_change.to_s
  end
0
source

All Articles