Feature #7654

Add optional code block to IO::readlines

Added by Володимир Шацький over 1 year ago. Updated about 1 year ago.

[ruby-core:51240]
Status:Open
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:core
Target version:next minor

Description

Of course, we always can write something like
File.readlines('/home/shock_one/test.rb').map{ |line| line.upcase }
but this way we create unneeded intermediate array which can be pretty big.
There is also a method IO::foreach, but it doesn't collect return values.
Besides it seems pretty logical and natural to have a block in this method.

History

#1 Updated by Володимир Шацький over 1 year ago

Just to be clear: code block will allow to write the first code snippet as follows:
data = File.readlines('/home/shock_one/test.rb'){ |line| line.upcase }

#2 Updated by Benoit Daloze over 1 year ago

Why not

File.foreach('test.rb').map { |line| line.upcase }

?
It does not create an intermediary Array.
If you need to do other operations lazily (without an intermediate result), you could use #lazy:

File.foreach('test.rb').lazy.select { |line| line.start_with? '/' }.map { |line| line.upcase }.to_a

#3 Updated by Benoit Daloze over 1 year ago

But of course the main memory usage here are likely String instances, so you could update them in place if possible:

File.foreach('test.rb').map { |line| line.upcase!; line }
# or
lines = File.readlines('test.rb')
lines.each(&:upcase!)

#4 Updated by Benoit Daloze over 1 year ago

(There is also Array#map!)

#5 Updated by Володимир Шацький over 1 year ago

Thank you, Eregon, especially for in place methods. I should definitely pay more attention to them - functional languages made me a little suspicious of this sort of things.
But I still think it would be nice to have an optional block in IO::readlines, at least for convenience. Enumerable#grep has similar behavior and I find it really cool and useful. Also this change doesn't break anything, is easy to implement and makes the code more concise.

#6 Updated by Koichi Sasada about 1 year ago

next minor issue or 2.0.0 issue?

#7 Updated by Eric Hodel about 1 year ago

I think next minor. It is a new feature but trunk is closed for new features.

#8 Updated by Eric Hodel about 1 year ago

  • Target version set to next minor

#9 Updated by Koichi Sasada about 1 year ago

  • Assignee set to Yukihiro Matsumoto

Also available in: Atom PDF