can you implement a better IO#each_lines?

H

Haoqi Haoqi

like this,thanks
#!/usr/bin/env ruby
class IO
def each_lines(n)
run=true
while run
lines=[]
n.times{
ln = self.gets
unless ln
run=false
break
else
lines<<ln.chomp
end
}
yield lines unless lines.empty?
end
end
end

open(__FILE__) do |f|
f.each_lines(3) do |lines|
p lines
end
end
 
D

David A. Black

Hi --

like this,thanks
#!/usr/bin/env ruby
class IO
def each_lines(n)
run=true
while run
lines=[]
n.times{
ln = self.gets
unless ln
run=false
break
else
lines<<ln.chomp
end
}
yield lines unless lines.empty?
end
end
end

open(__FILE__) do |f|
f.each_lines(3) do |lines|
p lines
end
end

require 'enumerator' # if necessary
open(__FILE__) do |f|
f.each_slice(3) do |lines|
p lines
end
end

:)


David

--
The Ruby training with D. Black, G. Brown, J.McAnally
Compleat Jan 22-23, 2010, Tampa, FL
Rubyist http://www.thecompleatrubyist.com

David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)
 
R

Robert Klemme

like this,thanks
#!/usr/bin/env ruby
class IO
def each_lines(n)
run=true
while run
lines=[]
n.times{
ln = self.gets
unless ln
run=false
break
else
lines<<ln.chomp
end
}
yield lines unless lines.empty?
end
end
end

open(__FILE__) do |f|
f.each_lines(3) do |lines|
p lines
end
end

There is no need to implement anything. You can use #each_slice:

robert@fussel:~$ seq 1 10 | ruby1.9 -e '$stdin.each_slice(3) {|l| p l}'
["1\n", "2\n", "3\n"]
["4\n", "5\n", "6\n"]
["7\n", "8\n", "9\n"]
["10\n"]
robert@fussel:~$

This works in 1.8.7 and 1.9.*.

Kind regards

robert
 
D

David A. Black

like this,thanks
#!/usr/bin/env ruby
class IO
def each_lines(n)
run=true
while run
lines=[]
n.times{
ln = self.gets
unless ln
run=false
break
else
lines<<ln.chomp
end
}
yield lines unless lines.empty?
end
end
end

open(__FILE__) do |f|
f.each_lines(3) do |lines|
p lines
end
end

There is no need to implement anything. You can use #each_slice:

robert@fussel:~$ seq 1 10 | ruby1.9 -e '$stdin.each_slice(3) {|l| p l}'
["1\n", "2\n", "3\n"]
["4\n", "5\n", "6\n"]
["7\n", "8\n", "9\n"]
["10\n"]
robert@fussel:~$

This works in 1.8.7 and 1.9.*.

And 1.8.6 if you require 'enumerator'.


David

--
The Ruby training with D. Black, G. Brown, J.McAnally
Compleat Jan 22-23, 2010, Tampa, FL
Rubyist http://www.thecompleatrubyist.com

David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top