In this article, you will learn how to use the Ruby sprintf method.
Using the sprintf method
The sprintf method in Ruby is used to format strings with placeholders. It works by taking a string and replacing the placeholders with the values provided as arguments. The placeholders are marked by percent signs (%) and are followed by a letter that determines the type of value that should be inserted.
Here’s an example of how to use the sprintf method in Ruby:
# Basic example age = 30 name = "John" formatted_string = sprintf("My name is %s and I am %d years old.", name, age) puts formatted_string # Output: "My name is John and I am 30 years old."
In this example, we’re using %s as a placeholder for a string value (the name variable) and %d as a placeholder for an integer value (the age variable).
Here are some of the most commonly used format specifiers with sprintf:
- %d: decimal (integer)
- %f: floating-point number
- %s: string
- %x: hexadecimal (integer)
You can also use additional options to specify the width and precision of the values being inserted. For example:
# Using width and precision options pi = 3.14159265359 formatted_string = sprintf("Pi is approximately %.2f", pi) puts formatted_string # Output: "Pi is approximately 3.14"
In this example, we’re using %.2f as a placeholder to insert a floating-point number with two decimal places.