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 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:
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?
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://w3resource.com/ruby-exercises/string/ruby-string-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics