How to get first line from String in Ruby?

first_line = str[/.*/]

This solution seems to be the most efficient solution in terms of memory allocation and performance.

This uses the str[regexp] form, see https://ruby-doc.org/core-2.6.5/String.html#method-i-5B-5D

Benchmark code:

require 'stringio'
require 'benchmark/ips'
require 'benchmark/memory'

str = "test\n" * 100

Benchmark.ips do |x|
  x.report('regex') { str[/.*/] }
  x.report('index') { str[0..(str.index("\n") || -1)] }
  x.report('stringio') { StringIO.open(str, &:readline) }
  x.report('each_line') { str.each_line.first.chomp }
  x.report('lines') { str.lines.first }
  x.report('split') { str.split("\n").first }
  x.compare!
end

Benchmark.memory do |x|
  x.report('regex') { str[/.*/] }
  x.report('index') { str[0..(str.index("\n") || -1)] }
  x.report('stringio') { StringIO.open(str, &:readline) }
  x.report('each_line') { str.each_line.first.chomp }
  x.report('lines') { str.lines.first }
  x.report('split') { str.split("\n").first }
  x.compare!
end

Benchmark results:

Comparison:
               regex:  5099725.8 i/s
               index:  4968096.7 i/s - 1.03x  slower
            stringio:  3001260.8 i/s - 1.70x  slower
           each_line:  2330869.5 i/s - 2.19x  slower
               lines:   187918.5 i/s - 27.14x  slower
               split:   182865.6 i/s - 27.89x  slower

Comparison:
               regex:         40 allocated
               index:        120 allocated - 3.00x more
            stringio:        120 allocated - 3.00x more
           each_line:        208 allocated - 5.20x more
               lines:       5064 allocated - 126.60x more
               split:       5104 allocated - 127.60x more

# Ruby >= 1.8.7
$varString.lines.first
# => "my::FIrst::Line"

# Ruby < 1.8.7
$varString.split("\n").first
# => "my::FIrst::Line"

As a side note, avoid to use global (the $ sign) variables.


$varString.lines.first

Or, if you want to get rid of final newline in resulting string:

$varString.lines.first.chomp

Tags:

Ruby