简体   繁体   中英

Ruby Count lines in file including last line(empty)

I'm trying to count the lines of a file with ruby but I can't get either IO or File to count the last line. What do I mean by last line? Here's a screenshot of Atom editor getting that last line 在此处输入图片说明

Ruby returns 20 lines, I need 21 lines. Here is such file https://copy.com/cJbiAS4wxjsc9lWI

Interesting question (although your example file is cumbersome). Your editor shows a 21st line because the 20th line ends with a newline character. Without a trailing newline character, your editor would show 20 lines.

Here's a simpler example:

a = "foo\nbar"
b = "baz\nqux\n"

A text editor would show:

# file a
1 foo
2 bar

# file b
1 baz
2 qux
3

Ruby however sees 2 lines in either cases:

a.lines       #=> ["foo\n", "bar"]
a.lines.count #=> 2

b.lines       #=> ["baz\n", "qux\n"]
b.lines.count #=> 2

You could trick Ruby into recognizing the trailing newline by adding an arbitrary character:

(a + '_').lines       #=> ["foo\n", "bar_"]
(a + '_').lines.count #=> 2

(b + '_').lines       #=> ["baz\n", "qux\n", "_"]
(b + '_').lines.count #=> 3

Or you could use a Regexp that matches either end of line ( $ ) or end of string ( \\Z ):

a.scan(/$|\Z/)       #=> ["", ""]
a.scan(/$|\Z/).count #=> 2

b.scan(/$|\Z/)       #=> ["", "", ""]
b.scan(/$|\Z/).count #=> 3

Ruby lines method doesn't count the last empty line. To trick, you can add an arbitrary character at the end of your stream.

Ruby lines returns 2 lines for this example:

1 Hello
2 World
3 

Instead, it returns 3 lines in this case

1 Hello
2 World
3 *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM