在Ruby中,可以使用多种方法来格式化字符串输出。以下是一些常用的方法:
name = "John"
age = 30
formatted_string = "My name is #{name} and I am #{age} years old."
puts formatted_string
String#format
方法:name = "John"
age = 30
formatted_string = "My name is %s and I am %d years old." % [name, age]
puts formatted_string
或者使用更现代的String#format
方法:
name = "John"
age = 30
formatted_string = "My name is %s and I am %d years old." % [name, age]
puts format(formatted_string, name: name, age: age)
sprintf
方法:name = "John"
age = 30
formatted_string = sprintf("My name is %s and I am %d years old.", name, age)
puts formatted_string
String#gsub
或String#sub
方法进行替换:name = "John"
age = 30
formatted_string = "My name is #{name.gsub("John", "Mike")} and I am #{age} years old."
puts formatted_string
这些方法都可以帮助你根据需要格式化字符串输出。根据你的需求和编程风格,可以选择最适合你的方法。