Home »
Ruby Tutorial
concat() method in Ruby
By IncludeHelp Last updated : December 01, 2024
Ruby provides you various ways through which you can join two or more strings and store it into another memory for future utilization. The concat() method is also one of them. It provides you a way through which you can join two or more string objects and store the result into the same memory. You can even store the resultant string object as well into another string object by assigning a value to it.
Description and Usage
The concat() method is considered as one of the fastest ways to carry out concatenation as it makes use of the same object to store the resultant string object. It makes the execution faster as compared to other ways of string concatenation.
It takes a string object or normal string as a parameter. If an integer value is provided to it, it implicitly converts it into the corresponding character depending upon its ASCII code.
Syntax
The concat() method is implemented in the following way:
String_Object.concat (String_Object)
Now let us go through its implementation in Ruby codes for a better understanding of the method.
Example 1
=begin
Ruby program to concat strings
using concat() method
=end
puts "Enter Any String"
str = gets.chomp
for i in 1..10
str.concat(rand(0..i).to_s);
end
puts "String with random numbers : #{str}"
Output
RUN 1:
Enter Any String
Cat
String with random numbers : Cat1101544150
RUN 2:
Enter Any String
Dog
String with random numbers : Dog1233522008
Explanation
In the above code, we are making use of the concat() method to add random numbers (which are generated by rand() method) with the string str. We have to convert the random number into string otherwise it will return the character associated with the ASCII value.
Example 2
=begin
Ruby program to concat strings
using concat method
=end
puts "Enter 10 names of the students"
str = ""
for i in 1..10
puts " #{i} Enter name:"
nam = gets.chomp
str.concat(nam.concat(" "))
end
puts "The names are #{str}"
Output
Enter 10 names of the students
1 Enter name:
Harish
2 Enter name:
Kranthi
3 Enter name:
j.Ai
4 Enter name:
Vibha
5 Enter name:
Namita
6 Enter name:
Rajiv
7 Enter name:
Vibha
8 Enter name:
Nityasha
9 Enter name:
Riya
10 Enter name:
Somya
The names are Harish Kranthi j.Ai Vibha Namita Rajiv Vibha Nityasha Riya Somya
Explanation
In the above code, we are calling the concat() method twice. One concat() method is being called under another concat() method. We are taking multiple names from the user inside the loop. In the last, we are printing the string object which has all the values entered by the user.