简体   繁体   中英

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

在Ruby语言中,如何获取字符串中的行数?

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.

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 }

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

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

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

String#chomp如果存在则删除行尾,-1允许空字符串。

这不会算空行:

string.split("\n").select{ |line| line != "" }.size

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