w3resource

Ruby Basic Exercises: Create a new string from a given string using the first three characters

Ruby Basic: Exercise-13 with Solution

Write a Ruby program to create a new string from a given string using the first three characters or whatever is there if the string is less than length 3. Return n copies of the string.

Ruby Basic Exercises: Create a new string from a given string using the first three characters

Ruby Code:

def multiple_string(str, n)
    str.length < 3 ? str*n : str[0..2]*n
end

print multiple_string('abcdefg', 1),"\n"
print multiple_string('abcdefg', 2),"\n"
print multiple_string('abcdef', 1),"\n"
print multiple_string('abcdef', 2),"\n"
print multiple_string('abc', 1),"\n"
print multiple_string('ab', 2),"\n"

Output:

abc
abcabc
abc
abcabc
abc
abab

Flowchart:

Flowchart: Create a new string from a given string using the first three characters

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a new string where "if" is added to the front of a given string. If the string already begins with "if", return the string unchanged.
Next: Write a Ruby program which accept the radius of the sphere as input and compute the volume.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/ruby-exercises/basic/ruby-basic-exercise-13.php