iboss
iboss

Reputation: 486

How can I redirect string to stdin in ruby

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

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

Is there any way to work this out?

Upvotes: 0

Views: 785

Answers (2)

matt
matt

Reputation: 79733

$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.

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).

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.

Upvotes: 2

2called-chaos
2called-chaos

Reputation: 3078

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:

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

Upvotes: 1

Related Questions