如何在Ruby中附加字符串?
有多种方法可以满足要求,但我们将研究其中的三种方法。
方法1:在预定义方法的帮助下concat()
这concat()是Ruby库中String类的预定义方法。此方法用于在两个String实例之间执行串联。
语法:
String1.concat(String2)
使用的变量:
Str1,Str2和Str3:这三个是String类的实例。Str1是要附加的String类对象。
程序:
=begin
Ruby program to append a String with the
help of concat() method.
=end
Str1 = "Nhooo"
Str2 = ".com"
puts "Str1 is #{Str1}"
puts "Str2 is #{Str2}"
Str3 = Str1.concat(Str2)
puts "The appended String object is #{Str3}"输出结果
Str1 is Nhooo Str2 is .com The appended String object is Nhooo.com
说明:
在上面的代码中,您可以观察到我们有三个字符串,分别为Str1,Str2和Str3。我们借助于String.concat方法将Str2附加到Str1中。我们将附加的String存储在Str3容器中。
方法2:在<<运算符的帮助下
在<<是String类在Ruby的库中预定义的方法/操作。此方法用于在两个String实例之间执行串联。
语法:
String1 << String2
使用的变量:
Str1,Str2和Str3:这三个是String类的实例。Str1是要附加的String类对象。
程序:
=begin
Ruby program to append a String with the
help of << operator.
=end
Str1 = "Nhooo"
Str2 = ".com"
Str3 = Str1<<Str2
puts "The appended String object is #{Str3}"输出结果
The appended String object is Nhooo.com
说明:
在上面的代码中,您可以观察到我们有三个字符串,分别为Str1,Str2和Str3。我们借助<<运算符将Str2追加到Str1中。我们将附加的String存储在Str3容器中。
方法3:在+运算符的帮助下
+是Ruby库中String类的预定义方法/运算符。此方法用于在两个String实例之间执行加法。添加也可以视为追加。
语法:
String3 = String1 + String2
与其他两种方法相比,这种方法效率较低,因为您需要一个临时存储区来存储结果字符串,而concat()and<<方法则不然。
使用的变量:
Str1,Str2和Str3:这三个是String类的实例。Str1是要附加的String类对象。
程序:
=begin
Ruby program to append a String with
the help of + operator.
=end
Str1 = "Nhooo"
Str2 = ".com"
Str3 = Str1 + Str2
puts "The appended String object is #{Str3}"输出结果
The appended String object is Nhooo.com
说明:
在上面的代码中,您可以观察到我们有三个字符串,分别为Str1,Str2和Str3。我们借助<<运算符将Str2追加到Str1中。我们将附加的String存储在Str3容器中。