Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to duplicate a string N times in Ruby

okwudili onyejiaku

Overview

We can use the asterisk * operator to duplicate a string for the specified number of times.

The asterisk operator returns a new string that contains a number of copies of the original string.

Syntax

string * int

Parameters

  • string: the string you want to duplicate.

  • int: the number of times that you want to duplicate the string.

Return value

The return value is a new string with n copies of the original string.

Code example

In the code below, we use the * operator to duplicate certain strings and print out the return values.

# create strings
str1 = "Heyyo!"
str2 = "Hi!"
str3 = "Edpresso"

# duplicate the strings
a = str1 * 2    # 2 times
b = str2 * 5    # 4 times
c = str3 * 7    # 7 times


puts a
puts b
puts c

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring