Skip to main content

RUBY – Using SPRINTF and PRINTF to format strings

By October 13, 2013September 12th, 2022No Comments

In this example we are going to take an IP Address in decimal format and convert the IP Address to Binary. The script itself it quite rudimentary but will will improve it in the next lesson where we look at defining methods in Ruby.

print "Enter an IP Address .. "
ips = gets.chomp
ipa = ips.split('.')
ipb1 = "%08b" % ipa[0]
ipb2 = "%08b" % ipa[1]
ipb3 = "%08b" % ipa[2]
ipb4 = "%08b" % ipa[3]
ipb = "#{ipb1}.#{ipb2}.#{ipb3}.#{ipb4}"
printf "%-14s %-35sn","Dotted Decimal","#{ips}"
printf "%-14s %-35sn","Binary", "#{ipb}"

The first new spot to visit is the method split that we use on line 5. We take the entered IP Address in the variable ips and with split we create an array which we store into the local variable ipa. So if we enter an address of we will have and array with 4 elements slit on the period or dot.

The fun begin when we format these decimal numbers to binary. Firstly lets consider the long-hand versions first.

ipb1 = sprintf "%b", ipa[0]

This populates ipb1 with the the binary version of the first array element. %b tells sprintf that we would like to format as binary. This is OK by itself if we have a number like 255 will will covert to 8 1s, 11111111. But the decimal 1 will convert to 1 in binary. to ensure we have 8 characters we pad with 0 and reserve 8 spaces. So it becomes:

ipb1 = sprintf "%08b", ipa[0]

As shorthand to this formatting with sprintf we can use the % operator in place of sprintf and move it between the format string and the array element as such:

ipb1 = "%08b" % ipa[0]

We then place the element back together:

ipb = "#{ipb1}.#{ipb2}.#{ipb3}.#{ipb4}"

If we wanted to we could be a little tidier and use the method join to take the array and reproduce the single dotted string. As we see from the following code instead of creating new variables for each array element we convert them in-place to binary and use join to recreate the string.

ipa = ips.split('.')
ipa[0] = "%08b" % ipa[0]
ipa[1] = "%08b" % ipa[1]
ipa[2]= "%08b" % ipa[2]
ipa[3] = "%08b" % ipa[3]
ipb = ipa.join('.')

The final two line use printf to print formatted information to the screen in this case. We are printing strings in both elements and we use the – the left-justify the text and allow for 14 and 35 character. this way are text is nicely lined up when it is displayed.

printf "%-14s %-35sn","Dotted Decimal","#{ips}"
printf "%-14s %-35sn","Binary", "#{ipb}"

The video demonstrates this tutorial for you.