string formattion ruby

String Formatting in Ruby

To format strings in Ruby, you can use various methods and techniques. Here is an explanation of each step involved in string formatting in Ruby:

  1. Concatenation: Concatenation is the process of combining strings together. In Ruby, you can use the + operator to concatenate strings. For example:

ruby str1 = "Hello" str2 = "World" result = str1 + " " + str2

The result variable will contain the string "Hello World".

  1. String Interpolation: String interpolation allows you to embed expressions or variables within a string. In Ruby, you can use the #{} syntax to interpolate values into a string. For example:

ruby name = "Alice" age = 25 message = "My name is #{name} and I am #{age} years old."

The message variable will contain the string "My name is Alice and I am 25 years old."

  1. Formatting with sprintf: The sprintf method allows you to format strings using placeholders and format specifiers. It is similar to the printf function in C. For example:

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

The formatted_string variable will contain the string "Name: Bob, Age: 30".

  1. Formatting with % operator: Ruby also provides the % operator for string formatting. It uses format specifiers to define the desired output format. For example:

ruby name = "Charlie" age = 35 formatted_string = "Name: %s, Age: %d" % [name, age]

The formatted_string variable will contain the string "Name: Charlie, Age: 35".

  1. Formatting with String#% method: The String#% method is similar to the % operator and allows you to format strings using placeholders and format specifiers. For example:

ruby name = "Dave" age = 40 formatted_string = "Name: %s, Age: %d" % [name, age]

The formatted_string variable will contain the string "Name: Dave, Age: 40".

These are some of the common techniques for string formatting in Ruby. You can choose the method that best suits your needs based on the specific formatting requirements.