Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

count

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

like image 283
Just a learner Avatar asked Apr 07 '10 04:04

Just a learner


People also ask

How do you count lines in a string?

To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);

How do you count strings in Ruby?

Ruby | String count() Method In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated. Parameters: Here, str is the given string.

What does \n do in Ruby?

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .

How do you get the first 3 characters of a string in Ruby?

To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .


2 Answers

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.

like image 136
Anurag Avatar answered Sep 23 '22 17:09

Anurag


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 } 
like image 39
mipadi Avatar answered Sep 23 '22 17:09

mipadi