How To Format String In Ruby

In this blog post, we will explore the different ways to format strings in Ruby. String formatting is a crucial part of any programming language as it allows manipulating and presenting strings in a human-readable and easily understandable format. In Ruby, there are several methods available to format strings, such as string interpolation, sprintf, and format.

String Interpolation

String interpolation is the most common method to format strings in Ruby. It allows you to embed expressions or variable values directly into a string using the #{} syntax. The expression inside the curly braces is evaluated and its result is automatically converted to a string and inserted in place.

Here’s a simple example:

name = "John"
age = 30
puts "My name is #{name} and I am #{age} years old."
    

Output:

My name is John and I am 30 years old.

sprintf and format

The sprintf and format methods are similar to the one used in C programming language. These methods allow you to create formatted strings with placeholders that are replaced by the specified values. The placeholders are represented by a percent sign (%) followed by a format specifier.

Here’s an example using sprintf:

name = "Jane"
age = 25
formatted_string = sprintf("My name is %s and I am %d years old.", name, age)
puts formatted_string
    

Output:

My name is Jane and I am 25 years old.

The format method works similarly to the sprintf method but is called directly on the String class.

Here’s an example using format:

name = "Jack"
age = 35
formatted_string = format("My name is %s and I am %d years old.", name, age)
puts formatted_string
    

Output:

My name is Jack and I am 35 years old.

Summary

In this blog post, we have discussed the different ways to format strings in Ruby. String interpolation is the most common method and is generally recommended for its simplicity and readability. However, the sprintf and format methods offer more control over the formatting process and might be useful in more complex situations.

Now that you know how to format strings in Ruby, you can easily manipulate and present your strings in a more user-friendly manner. Happy coding!