How to Use the Ruby concat Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby concat method.

Using the concat method

The Ruby concat method is a built-in method that allows you to append one or more strings to an existing string. The concat method is similar to the + operator, but it is more efficient when you need to append several strings to a string.

The concat method is available to all Ruby strings, and its syntax is straightforward. The method takes one or more arguments, which are the strings that you want to append to the original string. The concat method modifies the original string and returns it.

Syntax

Here is the syntax of the concat method:

string.concat(string1, string2, ...)

In this syntax, string is the original string, and string1, string2, etc. are the strings that you want to append to string.

Examples

Here is an example of using the concat method:

string = "Hello"
string.concat(" ", "World", "!")
puts string

In this example, the concat method appends a space, the string “World”, and an exclamation mark to the original string “Hello”. The result is the string “Hello World!”.

You can also use the concat method to append a string to itself. For example:

string = "Ruby is awesome!"
string.concat(" ", string)
puts string

In this example, the concat method appends the original string to itself, separated by a space. The result is the string “Ruby is awesome! Ruby is awesome!”.

If you want to append a string to itself a specific number of times, you can use a loop:

string = "Ruby is awesome!"
3.times { string.concat(" ", string) }
puts string

In this example, the loop appends the original string to itself three times, separated by a space. The result is the string “Ruby is awesome! Ruby is awesome! Ruby is awesome!”.

Finally, it’s important to note that the concat method modifies the original string in place. If you want to append strings without modifying the original string, you can use the + operator or the << operator instead.