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?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework