In Ruby language, how can I get the number of 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/);
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.
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 .
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 .
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With