Inconsistent behavior of IO/StringIO's each methods when called with nil as a separator, limit and chomp: true
IO's and StringIO's
#each method (and similar ones -
#readline etc) behave in a different way in the following case:
- separator is
- limit is passed
In this case
StringIO#each removes trailing
IO#each does not:
StringIO.new("abc\n\ndef\n").each(nil, 2, chomp: true).to_a #=> ["ab", "c", "\nd", "ef", ""] File.open('chomp.txt').each(nil, 2, chomp: true).to_a #=> ["ab", "c\n", "\nd", "ef", "\n"]
The file has the same content:
File.read('chomp.txt'); #=> "abc\n\ndef\n"
Expected behavior - both methods return the same result.
Updated by jeremyevans0 (Jeremy Evans) about 1 month ago
I think both IO#each and StringIO#each behavior is wrong when combining
chomp. My opinion is that a
nil separator means there is no separator at all, and therefore
chomp should either raise an error or be ignored if
nil is the separator. Assuming that ignoring
chomp is desired behavior for
nil separator, it follows:
IO#each behavior for
chompwith a limit is correct. However, IO#each for
chompwithout a limit is not, since it removes a final line separator.
StringIO#each behavior for
chompis wrong, regardless of whether a limit is used.
This issue is related to String#each_line, but the
chomp combination there is handled correctly, not removing any characters (it doesn't support limit).
Note that Ruby has current tests for the IO#each behavior for
chomp without limit removing the trailing line separator. So the current behavior for that is definitely expected, though I consider it undesirable.
Updated by jeremyevans (Jeremy Evans) 28 days ago
- Status changed from Open to Closed
Applied in changeset git|adaaf12857ce41d35b282e3fb5aa330934ce45c6.
[ruby/stringio] Ignore chomp keyword for nil separator
nil separator means no separator at all, so nothing should be
Partial fix for Ruby [Bug #18770]