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

20,109

Solution 1

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.

Solution 2

One way would be to count the number of line endings (\n or \r\n, depending on the string), the caveat being that if the string does not end in a new line, you'll have to make sure to add one to your count. You could do so with the following:

c = my_string.count("\n")
c += 1 unless c[-1,1] == "\n"

You could also just loop through the string and count the lines:

c = 0
my_string.each { |line| c += 1 }

Continuing with that solution, you could get really fancy and use inject:

c = my_string.each.inject(0) { |count, line| count += 1 }

Solution 3

string".split("\n").size works nicely. I like that it ignores trailing new-lines if they don't contain content.

"Hello\nWorld\n".split("\n") # => ["Hello", "World"]
"hello\nworld\nfoo bar\n\n".split("\n").size # => 3

That might not be what you want, so use lines() as @Anurag suggested instead if you need to honor all new-lines.

"hello\nworld\nfoo bar\n\n".lines.count # => 4

Solution 4

"hello\nworld\nfoo bar\n\n".chomp.split("\n",-1).size # => 4

String#chomp gets rid of an end of line if it exists, and the -1 allows empty strings.

Solution 5

given a file object (here, in rails)

file = File.open(File.join(Rails.root, 'lib', 'file.json'))
file.readlines.count

returns the number of lines

IO#readlines performs a split method on strings (IOStrings in this case) using newlines as the separator

Share:
20,109
Just a learner
Author by

Just a learner

Updated on October 09, 2020

Comments

  • Just a learner
    Just a learner over 3 years

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