Skip to content

Commit

Permalink
Prefer block version of File.open in io.rb
Browse files Browse the repository at this point in the history
This removes the need to manually close the file descriptor, and still
closes it if an exception occurs in the block.
  • Loading branch information
herwinw committed Oct 8, 2023
1 parent 09014c1 commit 13d2489
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions src/io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,21 @@ def foreach(path, *args, **opts)

mode = opts.delete(:mode) || 'r'
chomp = opts.delete(:chomp)
io = File.open(path, mode, **opts)
io.each_line(*args, **opts.merge(chomp: chomp)) do |line|
$_ = line
yield line
File.open(path, mode, **opts) do |io|
io.each_line(*args, **opts.merge(chomp: chomp)) do |line|
$_ = line
yield line
end
end
io.close
$_ = nil
end

def readlines(path, *args, **opts, &block)
mode = opts.delete(:mode) || 'r'
chomp = opts.delete(:chomp)
io = File.open(path, mode, **opts)
result = io.each_line(*args, **opts.merge(chomp: chomp), &block).to_a
io.close
result
File.open(path, mode, **opts) do |io|
io.each_line(*args, **opts.merge(chomp: chomp), &block).to_a
end
end
end

Expand Down

0 comments on commit 13d2489

Please sign in to comment.