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
.
We can use operators to append and duplicate strings. Most programs do not need complex concatenations, but they are sometimes helpful.
Concat
exampleTo begin we concatenate 2 strings. We add 2 string
variables, value1 and value2, along with the "/" literal. We display the result.
# Two string values. value1 = "Ruby" value2 = "Python" # Concatenate the string values. value3 = value1 + "/" + value2; # Display the result. puts value3Ruby/Python
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 + " ") * 3banana 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
.
string
. So after we append once, the actual string
data is changed.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 valuecat cat in cat in the hat
We can use concatenation and append on string
variables and string
literals. Many Ruby programs will need to append or combine strings.