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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)