tags:

views:

212

answers:

4

Hi guys,

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

+2  A: 

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 }
mipadi
+10  A: 

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.

Anurag
"Hello\nWorld\n".lines.to_a # => ["Hello\n", "World\n"]Note, the newlines are not ignored, they are included with the line.
Greg
Greg, I meant the very last newline is ignored for the purposes of counting number of lines.
Anurag
This doesn't work in ruby 1.8.6 .
Andrew Grimm
@Andrew, you're right. For Ruby 1.8.6 and prior versions, you'd have to use `count`, `each`, `each_line`, `split` or one of the many other ways as suggested by @mipadi and @Greg.
Anurag
+1  A: 

"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
Greg
A: 

"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.

Andrew Grimm