How can I read multiple lines at a time from a file in Ruby?
I tried using each_slice(2)
and also did: require 'enumerator'
, but it doesn't work. I get the following error:
undefined method `each_slice' for #<String:0x877d12c> (NoMethodError)
Both IO
and String
have a lines
enumerator, which you can call each_slice
on:
irb(main):004:0> STDIN.lines.each_slice(2).take(2)
a
a
b
c
=> [["a\n", "a\n"], ["b\n", "c\n"]]
Of course you can substitute STDIN
with any other IO
instance (open file). Demo with a string:
irb(main):005:0> "a\na\nb\nc".lines.each_slice(2).to_a
=> [["a\n", "a\n"], ["b\n", "c"]]
Both of these work in Ruby >= 1.8.7
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.