如何在ruby中将字符串重定向到stdin

时间:2021-12-18 07:26:26

I need to do something like this.

我需要做这样的事情。

10.times do |i|
    file = File.open("./data/#{i+1}.in")
    $stdin = file.read
    load 'sum.rb'
    file.close
end

And this is sum.rb

这是sum.rb

gets.chomp.split().map { |e| e.to_i }
puts array.inject(:+)

Is there any way to work this out?

有没有办法解决这个问题?

2 个解决方案

#1


2  

$stdin and the result of File.open are both IO objects, so rather than assign the results of file.read to $stdin, assign file itself.

$ stdin和File.open的结果都是IO对象,因此不是将file.read的结果赋给$ stdin,而是分配文件本身。

10.times do |i|
    file = File.open("./data/#{i+1}.in")
    $stdin = file
    load 'sum.rb'
    file.close
end

This will fix your immediate problem, your sum.rb won’t work as it is (array isn’t defined anywhere).

这将解决您的直接问题,您的sum.rb将无法正常工作(数组未在任何地方定义)。

In a more robust version of this you would probably want to retain the original value of $stdin and reset it after you are finished.

在更强大的版本中,您可能希望保留$ stdin的原始值并在完成后重置它。

#2


1  

Maybe there is an easier way but if you don't mind to spawn sum.rb as a new process (which would simulate a test better imho) you could do it like this:

也许有一种更简单的方法但是如果你不介意将sum.rb生成为一个新进程(它可以模拟一个更好的imho测试),你可以这样做:

require "open3"

10.times do |i|
  File.open("./data/#{i+1}.in") do |file|
    Open3.popen2e("ruby sum.rb") do |stdin, stdout, wait_thr|
      stdin.puts(file.read)
      exit_status = wait_thr.value # Process::Status object returned.
    end
  end
end

Doc: http://ruby-doc.org/stdlib-2.1.0/libdoc/open3/rdoc/Open3.html#method-c-popen2e

Doc:http://ruby-doc.org/stdlib-2.1.0/libdoc/open3/rdoc/Open3.html#method-c-popen2e

#1


2  

$stdin and the result of File.open are both IO objects, so rather than assign the results of file.read to $stdin, assign file itself.

$ stdin和File.open的结果都是IO对象,因此不是将file.read的结果赋给$ stdin,而是分配文件本身。

10.times do |i|
    file = File.open("./data/#{i+1}.in")
    $stdin = file
    load 'sum.rb'
    file.close
end

This will fix your immediate problem, your sum.rb won’t work as it is (array isn’t defined anywhere).

这将解决您的直接问题,您的sum.rb将无法正常工作(数组未在任何地方定义)。

In a more robust version of this you would probably want to retain the original value of $stdin and reset it after you are finished.

在更强大的版本中,您可能希望保留$ stdin的原始值并在完成后重置它。

#2


1  

Maybe there is an easier way but if you don't mind to spawn sum.rb as a new process (which would simulate a test better imho) you could do it like this:

也许有一种更简单的方法但是如果你不介意将sum.rb生成为一个新进程(它可以模拟一个更好的imho测试),你可以这样做:

require "open3"

10.times do |i|
  File.open("./data/#{i+1}.in") do |file|
    Open3.popen2e("ruby sum.rb") do |stdin, stdout, wait_thr|
      stdin.puts(file.read)
      exit_status = wait_thr.value # Process::Status object returned.
    end
  end
end

Doc: http://ruby-doc.org/stdlib-2.1.0/libdoc/open3/rdoc/Open3.html#method-c-popen2e

Doc:http://ruby-doc.org/stdlib-2.1.0/libdoc/open3/rdoc/Open3.html#method-c-popen2e