Hi guys,
In Ruby language, how can I get the number of lines in a string?
Hi guys,
In Ruby language, how can I get the number of lines in a string?
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 }
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.
"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").to_a # => ["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
"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.