在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
或者使用更現(xiàn)代的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
方法進(jìn)行替換:name = "John"
age = 30
formatted_string = "My name is #{name.gsub("John", "Mike")} and I am #{age} years old."
puts formatted_string
這些方法都可以幫助你根據(jù)需要格式化字符串輸出。根據(jù)你的需求和編程風(fēng)格,可以選擇最適合你的方法。