Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IO#write accepts multiple arguments #4999

Merged
merged 2 commits into from Jan 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions core/src/main/java/org/jruby/RubyIO.java
Expand Up @@ -1450,6 +1450,15 @@ public IRubyObject write(ThreadContext context, IRubyObject str) {
return write(context, str, false);
}

@JRubyMethod(name = "write", rest = true)
public IRubyObject write(ThreadContext context, IRubyObject[] args) {
long bytes = Arrays.stream(args)
.map(s -> write(context, s, false))
.map(n -> RubyNumeric.num2long(n))
.reduce(0l, (x, y) -> x + y);
return RubyFixnum.newFixnum(context.runtime, bytes);
}

// io_write
public IRubyObject write(ThreadContext context, IRubyObject str, boolean nosync) {
Ruby runtime = context.runtime;
Expand Down
57 changes: 57 additions & 0 deletions test/mri/ruby/test_io.rb
Expand Up @@ -1203,6 +1203,63 @@ def test_ungetc2
end)
end

def test_write_with_multiple_arguments
pipe(proc do |w|
w.write("foo", "bar")
w.close
end, proc do |r|
assert_equal("foobar", r.read)
end)
end

def test_write_with_multiple_arguments_and_buffer
mkcdtmpdir do
line = "x"*9+"\n"
file = "test.out"
open(file, "wb") do |w|
w.write(line)
assert_equal(11, w.write(line, "\n"))
end
open(file, "rb") do |r|
assert_equal([line, line, "\n"], r.readlines)
end

line = "x"*99+"\n"
open(file, "wb") do |w|
w.write(line*81) # 8100 bytes
assert_equal(100, w.write("a"*99, "\n"))
end
open(file, "rb") do |r|
81.times {assert_equal(line, r.gets)}
assert_equal("a"*99+"\n", r.gets)
end
end
end

def test_write_with_many_arguments
[1023, 1024].each do |n|
pipe(proc do |w|
w.write(*(["a"] * n))
w.close
end, proc do |r|
assert_equal("a" * n, r.read)
end)
end
end

def test_write_with_multiple_nonstring_arguments
assert_in_out_err([], "STDOUT.write(:foo, :bar)", ["foobar"])
end

def test_write_buffered_with_multiple_arguments
out, err, (_, status) = EnvUtil.invoke_ruby(["-e", "sleep 0.1;puts 'foo'"], "", true, true) do |_, o, e, i|
[o.read, e.read, Process.waitpid2(i)]
end
assert_predicate(status, :success?)
assert_equal("foo\n", out)
assert_empty(err)
end

def test_write_non_writable
with_pipe do |r, w|
assert_raise(IOError) do
Expand Down