How to Multiply Strings in Ruby: Syntax and Examples
In Ruby, you multiply a string by an integer using the
* operator, like string * number. This repeats the string the specified number of times, producing a new string.Syntax
The syntax to multiply a string in Ruby is simple: use the * operator between a string and an integer.
string: The text you want to repeat.*: The multiplication operator for strings.number: How many times to repeat the string (must be a non-negative integer).
ruby
result = "hello" * 3 puts result
Output
hellohellohello
Example
This example shows how to multiply the string "abc" by 4, which repeats "abc" four times in a row.
ruby
word = "abc" repeated = word * 4 puts repeated
Output
abcabcabcabc
Common Pitfalls
Common mistakes include multiplying a string by a non-integer or negative number, which will cause errors or unexpected results.
Also, multiplying by zero returns an empty string.
ruby
begin puts "test" * -1 rescue ArgumentError => e puts "Error: #{e.message}" end puts "test" * 0
Output
Error: negative argument
Quick Reference
| Operation | Description | Example | Result |
|---|---|---|---|
| Multiply string by positive integer | Repeats the string that many times | "hi" * 3 | "hihihi" |
| Multiply string by zero | Returns an empty string | "hi" * 0 | "" |
| Multiply string by negative integer | Raises an error | "hi" * -1 | ArgumentError |
Key Takeaways
Use the * operator to multiply a string by a non-negative integer in Ruby.
Multiplying by zero returns an empty string.
Multiplying by a negative number raises an ArgumentError.
The result is a new string with the original repeated the specified times.