Concat, Append StringsConcatenate and append strings with the plus and append operators. Multiple strings together.
This page was last reviewed on Sep 15, 2023.
Concatenate. Two or more strings can be combined into one. This is called concatenation. In Ruby we use the plus operator—we add strings together. This yields a new string.
Syntax notes. We can use "<<" to append strings, and "*" to duplicate strings. Most programs do not need complex concatenations, but they are sometimes helpful.
Concat example. To begin we concatenate 2 strings. We add 2 string variables, value1 and value2, along with the "/" literal. We display the result.
String Literal
# Two string values. value1 = "Ruby" value2 = "Python" # Concatenate the string values. value3 = value1 + "/" + value2; # Display the result. puts value3
Multiplication. Suppose we want to duplicate a string 2 or more times. We may want to repeat a pattern or word. We can multiply a string in Ruby.
# Use multiplication to concatenate a string many times. result = "ba" + "na" * 2 puts result # Write the string 3 times. puts (result + " ") * 3
banana banana banana banana
Append. Ruby has a special syntax for string appends. It uses the "<<" operator. We can use this operator to combine two or more strings. Here we append twice to a single string.
Tip The append operator changes the value of the string. So after we append once, the actual string data is changed.
Tip 2 If you want to retain the original data, you can copy a string by assigning another string reference to it.
value = "cat" puts value # Append this string (surrounded by spaces). value << " in " puts value # Append another string. value << "the hat" puts value
cat cat in cat in the hat
A summary. We can use concatenation and append on string variables and string literals. Many Ruby programs will need to append or combine strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.