How to Use the Ruby printf Method



In this article, you will learn how to use the Ruby printf method.

Using the printf Method

The printf method in Ruby is used to format strings with specific placeholders for various types of data. It works in a similar way to the printf function in other programming languages like C and Java.


The general syntax of the printf method is:

printf(format_string, arguments...)

Here, format_string is a string that contains placeholders for the values of the arguments that follow. The placeholders start with a % character, followed by a format specifier that defines the type of data to be inserted.

Some of the commonly used format specifiers are:

  • %d – for integer values
  • %f – for floating-point values
  • %s – for string values
  • %c – for character values
  • %x – for hexadecimal values
  • %o – for octal values


To use printf, you can pass the format string and arguments as arguments to the method. For example:

age = 25
name = "John Doe"

printf("Name: %s, Age: %d", name, age)

This will output: Name: John Doe, Age: 25

You can also include additional formatting options within the format specifier, such as the width of the field, the precision of a floating-point value, and the justification of the field.

Here are some examples:

# Display an integer with a width of 5 characters, right-justified
printf("%5d", 123)

# Output: "  123"

# Display a floating-point value with a precision of 2 decimal places
printf("%.2f", 3.14159)

# Output: "3.14"

# Display a string with a width of 10 characters, left-justified
printf("%-10s", "Hello")

# Output: "Hello     "

You can also combine multiple format specifiers in the same format string:

# Display a string and an integer value with a width of 10 characters each
printf("%-10s%10d", "Hello", 123)

# Output: "Hello           123"

In addition to printf, Ruby also provides the sprintf method, which returns a formatted string instead of outputting it to the console:

age = 25
name = "John Doe"

formatted_string = sprintf("Name: %s, Age: %d", name, age)

puts formatted_string

This will output: Name: John Doe, Age: 25