Home
Ruby
String Concat, Append
Updated Sep 15, 2023
Dot Net Perls
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 operators to append and 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
Ruby/Python
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 shift 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen