Ruby – In Ruby language, how can I get the number of lines in a string

countrubystring

In Ruby language, how can I get the number of lines in a string?

Best Answer

There is a lines method for strings which returns an Enumerator. Call count on the enumerator.

str = "Hello\nWorld"
str.lines.count # 2

str = "Hello\nWorld\n" # trailing newline is ignored
str.lines.count # 2

The lines method was introduced in Ruby 1.8.7. If you're using an older version, checkout the answers by @mipadi and @Greg.