diff --git a/NEWS b/NEWS index be51f55178..cf17e42345 100644 --- a/NEWS +++ b/NEWS @@ -44,6 +44,7 @@ with all sufficient information, see the ChangeLog file or Redmine * IO#pread [Feature #4532] * IO#pwrite [Feature #4532] + * IO#reopen takes a block [Feature #2631] * IOError diff --git a/io.c b/io.c index 3482602326..8b0064b2dc 100644 --- a/io.c +++ b/io.c @@ -7058,6 +7058,10 @@ rb_io_reopen(int argc, VALUE *argv, VALUE file) } } + if (rb_block_given_p()) { + return rb_ensure(rb_yield, file, io_close, file); + } + return file; } diff --git a/test/ruby/test_io.rb b/test/ruby/test_io.rb index 791e52b500..186c148159 100644 --- a/test/ruby/test_io.rb +++ b/test/ruby/test_io.rb @@ -2156,6 +2156,22 @@ class TestIO < Test::Unit::TestCase } end + def test_reopen_with_block + make_tempfile {|t| + open(__FILE__) do |f| + f.gets + assert_nothing_raised { + reopened = nil + f.reopen(t.path) do |_reopened| + reopened = _reopened + assert_equal("foo\n", reopened.gets) + end + assert_equal(true, reopened.closed?) + } + end + } + end + def test_reopen_inherit mkcdtmpdir { system(EnvUtil.rubybin, '-e', <<"End")