w3resource

Ruby String Exercises: Truncate a given string to the first n words

Ruby String: Exercise-17 with Solution

Write a Ruby program to truncate a given string to the first n words.

Ruby String Exercises: Truncate a given string to the first n words

Ruby Code:

str = "Python is a  widely used   high-level, general-purpose,
interpreted, dynamic programming language.
Its design philosophy emphasizes code readability, 
and its syntax allows programmers to express concepts in
fewer lines of code than possible in languages such 
as C++ or Java."
n = 3
print str.split[0...n].join(' ')
n = 8
print "\n",str.split[0...n].join(' ')
n = 11
print "\n",str.split[0...n].join(' ')

Output:

Python is a
Python is a widely used high-level, general-purpose, interpreted,
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.

Flowchart:

Flowchart: Truncate a given string to the first n words

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to get the number of lines in a given string.
Next: Write a Ruby program to remove a character from a given string if it starts with that specified character.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.