Another option is to use String # chomp , which also by itself processes newlines.
You can accomplish what you need with something like:
lines = string.lines.map(&:chomp)
Or if you are dealing with something big enough to use memory:
<string|io>.each_line do |line| line.chomp! # do work.. end
Performance is not always the most important thing when solving this kind of problem, but it is worth noting that the chomp solution is also slightly faster than using a regular expression.
On my machine (i7, ruby ββ2.1.9):
Warming up -------------------------------------- map/chomp 14.715ki/100ms split custom regex 12.383ki/100ms Calculating ------------------------------------- map/chomp 158.590k (Β± 4.4%) i/s - 794.610k in 5.020908s split custom regex 128.722k (Β± 5.1%) i/s - 643.916k in 5.016150s
Matt Sanders Aug 16 '16 at 23:34 2016-08-16 23:34
source share