Skip to content

Commit

Permalink
IO#each_line: return enumerator when no block is given
Browse files Browse the repository at this point in the history
  • Loading branch information
floriandejonckheere committed Oct 20, 2023
1 parent 3a44f15 commit 90fb3b0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/polyphony/extensions/io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,9 @@ def gets(sep = $/, _limit = nil, _chomp: nil)
end

# @!visibility private
def each_line(sep = $/, limit = nil, chomp: false)
def each_line(sep = $/, limit = nil, chomp: false, &block)
return to_enum(:each_line, sep, limit, chomp: chomp) unless block_given?

if sep.is_a?(Integer)
limit = sep
sep = $/
Expand Down
27 changes: 27 additions & 0 deletions test/test_io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,33 @@ def test_getbyte
assert_equal [102, 103], buf
end

def test_each_line_with_block
file = Tempfile.new
file << "foo\nbar\nbaz\n"
file.close

strings = ["foo\n", "bar\n", "baz\n"]

i = 0
File.open(file, 'r').each_line do |line|
assert_equal line, strings[i]

i += 1
end
end

def test_each_line_iterator
file = Tempfile.new
file << "foo\nbar\nbaz\n"
file.close

it = File.open(file, 'r').each_line

assert_equal it.next, "foo\n"
assert_equal it.next, "bar\n"
assert_equal it.next, "baz\n"
end

# see https://github.com/digital-fabric/polyphony/issues/30
def test_reopened_tempfile
file = Tempfile.new
Expand Down

0 comments on commit 90fb3b0

Please sign in to comment.