Home »
Ruby Tutorial
How to append a String in Ruby?
By IncludeHelp Last updated : December 01, 2024
There are multiple ways to do the required but we will study about three of them.
Appending string using predefined method concat()
The concat() is a predefined method for String class in Ruby's library. This method is used for carrying out concatenation between two String instances.
Syntax
String1.concat(String2)
Variables used:
Str1, Str2 and Str3: The three are the instances of String class. Str1 is the String class object which is going to be appended.
Example
=begin
Ruby program to append a String with the
help of concat() method.
=end
Str1 = "Includehelp"
Str2 = ".com"
puts "Str1 is #{Str1}"
puts "Str2 is #{Str2}"
Str3 = Str1.concat(Str2)
puts "The appended String object is #{Str3}"
Output
Str1 is Includehelp
Str2 is .com
The appended String object is Includehelp.com
Explanation
In the above code, you can observe that we have three strings namely Str1, Str2, and Str3. We are appending Str2 into Str1 with the help of String.concat method. We are storing the appended String in Str3 container.
Appending string using << operator
The << is a predefined method/operator for String class in Ruby's library. This method is used for carrying out concatenation between two String instances.
Syntax
String1 << String2
Variables used:
Str1, Str2, and Str3: The three are the instances of String class. Str1 is the String class object which is going to be appended.
Example
=begin
Ruby program to append a String with the
help of << operator.
=end
Str1 = "Includehelp"
Str2 = ".com"
Str3 = Str1<<Str2
puts "The appended String object is #{Str3}"
Output
The appended String object is Includehelp.com
Explanation
In the above code, you can observe that we have three strings namely Str1, Str2, and Str3. We are appending Str2 into Str1 with the help of << operator. We are storing the appended String in Str3 container.
Appending string using + operator
The + is a predefined method/operator for String class in Ruby's library. This method is used to carry out addition between two String instances. Adding can be considered as appending as well.
Syntax
String3 = String1 + String2
This way is less efficient in comparison with other two because you need to have a temporary storage to store the resultant String which is not the case of concat() and << method.
Variables used:
Str1, Str2 and Str3: The three are the instances of String class. Str1 is the String class object which is going to be appended.
Example
=begin
Ruby program to append a String with
the help of + operator.
=end
Str1 = "Includehelp"
Str2 = ".com"
Str3 = Str1 + Str2
puts "The appended String object is #{Str3}"
Output
The appended String object is Includehelp.com
Explanation
In the above code, you can observe that we have three strings namely Str1, Str2, and Str3. We are appending Str2 into Str1 with the help of << operator. We are storing the appended String in Str3 container.