w3resource

Ruby String Exercises: Get the number of lines in a given string

Ruby String: Exercise-16 with Solution

16. Write a Ruby program to get the number of lines in a given string.

Ruby String Exercises: Get the number of lines in a given string

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."
print "Number of lines of the above string: ",str.lines.count

Output:

Number of lines of the above string: 6

Flowchart:

Flowchart: Get the number of lines in a given string

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to get a substring from a specified position to the last char of a given string.
Next: Write a Ruby program to truncate a given string to the first n words.

What is the difficulty level of this exercise?