在Ruby中,有多種方法可以實現(xiàn)字符串拼接。以下是一些常見的方法:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
puts result # 輸出 "Hello World"
name = "Alice"
age = 30
result = "My name is #{name} and I am #{age} years old."
puts result # 輸出 "My name is Alice and I am 30 years old."
name = "Alice"
age = 30
result = "My name is %s and I am %d years old." % [name, age]
puts result # 輸出 "My name is Alice and I am 30 years old."
concat
方法:str1 = "Hello"
str2 = "World"
result = str1.concat(" ")
result.concat(str2)
puts result # 輸出 "Hello World"
<<
操作符(將一個字符串添加到另一個字符串的末尾):str1 = "Hello"
str2 = "World"
result = str1 << " " << str2
puts result # 輸出 "Hello World"
這些方法都可以實現(xiàn)字符串拼接,你可以根據(jù)自己的需求和喜好選擇合適的方法。