Ruby Sprintf: An Easy, Versatile Way to Format Strings

ruby sprintfRuby was created in 1993 by Matsumoto.  The syntax of Ruby is simple and easy. It is one of the reasons for its tremendous popularity. A new developer will definitely find it easy to learn this important and useful programming language. This language is object-oriented and is also used for server side scripting. Ruby has features which are like that of Smalltalk, Perl and Python.  It is open source, but subject to a license.

Ruby IO forms an important part of the Ruby programming language. It provides a rich set of functions which enables Ruby programmers to create useful and elegant programs. The sprintf function is an important IO function which is widely used in Ruby programs. Today we walk you through the sprintf function. We assume that you are aware about the basics of Ruby programming. Even if you do not have prior programming experience, this special course on Ruby can help get you up to speed in no time (well, almost!). If you just need a quick brush up on Ruby, you can read through our step by step guide to learning Ruby.

What is Sprintf?

You may be familiar with the Ruby printf function (you can read more about Ruby print in this deep dive tutorial). Conceptually, sprintf is pretty similar to printf. The major difference is that instead of printing to the screen, sprintf saves the formatted text into a string variable. The syntax of format function is as follows

sprintf( format sequence[, argument])

This returns a string in which the argument is formatted according to a format  sequence. The syntax of a format sequence is follows

%[flags][width][.precision]type

A format sequence has a “%” sign which is followed by optional flags, width and precision indicators. The sequence is terminated with a field type character.

The table here displays the field type characters:

FieldDescription
bThe argument is converted to a binary number.
BSimilar to ‘b.’ However, uses an uppercase OB for prefix.
 dArgument is converted into a decimal number.
isame as ‘d’
oArgument is converted into an octal number.
usame as ‘d’
xArgument is converted into a hexadecimal number. The negative numbers are displayed with prefix f

 

Have a look at the following table. Here the field is of type Float:

FieldDescription
econverts the floating point argument to exponential format.
ESame as ‘e.’ However, uses the uppercase E to for exponent
fConverts floating point argument to decimal format along with the number of digits after the decimal point.
gIt converts a floating point number which uses exponential form
GSame as ‘g.’ However it uses an uppercase ‘E’ in exponent format.
aConverts a floating point argument with  fraction part as a hexadecimal and exponential part as decimal.
ASame as “a.” However uses uppercase ‘X’ and ‘P’.

 

The other formats are covered in the following table:

FieldDescription
cArgument is either a number code for an individual character or an individual character string itself. 
pevaluates argument.inspect
sIts argument is a string to be substituted.
%Does not accept any argument. The % sign will itself be displayed.

To learn more about Ruby print and sprintf formats, you can look up this practical training course.

Examples of the Ruby Sprintf Function

To return integer values –  %d

  • sprintf(“%d”, 456)  #=> “456” – This simply prints out the integer value which is 456
  • sprintf(“%+d”, 456) #=> “+456” –  Prints the plus sign preceding the integer.
  • sprintf(“% d”, 456) #=> ” 456″ – Prints the space preceding the integer.

To return octal values – % o

  • sprintf(“%o”, 456)   #=> “710” – This example prints out the octal value of the decimal integer.
  • sprintf(“%#o”, 456)  #=> “0710” – In this example the octal value is preceded by a zero
  • sprintf(“%+o”, -456) #=> “-710” –  Prints the minus sign preceding the octal value
  • sprintf(“%o”, -123)  #=> “..7605” – Prints the twos complement of the negative decimal preceded by ..7.
  • sprintf(“%#o”, -123) #=> “..7605”- This result is similar to the above example.

To return hexadecimal values- %x and %X

  • sprintf(“%x”, 456) #=> “1c8” – Prints the hexadecimal value of the decimal integer.
  • sprintf(“%#x”, 456)  #=> “0x1c8” – Value is same as the above. However, the hexadecimal value is preceded by the hexadecimal notation “0x”
  • sprintf(“%+x”, -456) #=> “-1c8” – Prints the negative sign before the hexadecimal value.
  • sprintf(“%x”, -123)  #=> “..f85” – The value printed is the two’s complement of the decimal value. Also note that it is preceded by “..f”
  • sprintf(“%#x”, -123) #=> “0x..f85” – The result is same as above. However, the hexadecimal notation precedes the result.
  • sprintf(“%#x”, 0)    #=> “0” –  Since it’s a zero value, the hexadecimal notation is not used.
  • sprintf(“%X”, 456)  #=> “1C8” – This command prints  uppercase letters in the result.
  • sprintf(“%#X”, 456) #=> “0X1C8” –The hexadecimal value is printed using uppercase and is also preceded by the hexadecimal notation in uppercase.

To learn more about how to print and format different strings in Ruby, check out this course.

To return binary values- %b and % B are used

  • sprintf(“%b”, 456)   #=> “111001000”- Prints the binary value of the decimal integer
  • sprintf(“%#b”, 456)  #=> “0b111001000” – Prints the binary value prefixed by binary notation “0b”
  • sprintf(“%+b”, -456) #=> “-111001000”- Prints the binary value prefixed by minus sign
  • sprintf(“%b”, -123)  #=> “..10000101” – Prints the twos complement of the decimal integer prefixed by “..1”
  • sprintf(“%#b”, -123) #=> “0b..10000101” – same as above example and prefixed by binary notation “0b”.
  • sprintf(“%#b”, 0)    #=> “0”- since the decimal is zero the result is not prefixed by binary notation “0b”.
  • sprintf(“%B”, 123)  #=> “111001000”- prints the binary value of the decimal integer
  • sprintf(“%#B”, 123) #=> “0B111001000”- Prints the binary value prefixed by binary notation in upper case letters“0B”

To return exponential –  %e is used for exponential format

  • sprintf(“%.0e”, 1)  #=> “1e+00”- converts floating point number into exponential notation
  • sprintf(“%#.0e”, 1) #=> “1.e+00”- same as above example and includes the decimal point

% f and %g is used to print floating point values.

  • sprintf(“%.0f”, 1234)  #=> “1234”
  • sprintf(“%#.0f”, 1234) #=> “1234.”- The use of # in the argument causes the decimal point to be displayed
  • sprintf(“%g”, 456.7)   #=> “456.7”
  • sprintf(“%#g”, 456.7)  #=> “456.700” The use of # in the argument causes the decimal point to be displayed.  Also it disables the lowest zeros being stripped
  • sprintf(“%g”, 456789)  #=> “456789”
  • sprintf(“%#g”, 456789) #=> “456789.” The use of # in the argument causes the decimal point to be displayed.

The field width is optional. The field may be followed by a period and a precision. It specifies the minimum number of characters which will come in the spaces.

  • sprintf(“%20d”, 456)   #=> ”                 456″ The width of the result is 20 for this example and the examples which follow.
  • sprintf(“%+20d”, 456)  #=> ”                +456″ The plus sign is included in the result.
  • sprintf(“%020d”, 456)  #=> “00000000000000000456” The spaces are all replaced by instances of  the zero integer.
  • sprintf(“%+020d”, 456) #=> “+0000000000000000456” – result is same as above but prefixed by the plus sign.
  • sprintf(“% 020d”, 456) #=> ” 0000000000000000456″- result prefixed by space character
  • sprintf(“%-20d”, 456)  #=> “456                 ” In this result the value is displayed in the beginning followed by specified width of spaces
  • sprintf(“%-+20d”, 456) #=> “+456                “Same as above example but prefixed by plus sign
  • sprintf(“%-  20d”, 456) #=> ” 456               “result prefixed by space character

The sprintf  function is a versatile and useful function which helps the programmer to display the output appropriately. Go through the examples above to get exposure to the power and range of this function. We strongly encourage you to experiment and try these code snippets on your own. That’s the best way to learn. You can also take this special course designed to help you learn Ruby from scratch. It’s a good way to start and find your element. Once you’re more comfortable and read to move to the next level, you can take this advanced Ruby course to gain mastery!