sum.rb
is very simple. You input two numbers and it returns the sum.
# sum.rb
puts "Enter number A"
a = gets.chomp
puts "Enter number B"
b = gets.chomp
puts "sum is #{a.to_i + b.to_i}"
robot.rb
used Open3.popen3
to interact with sum.rb
. Here's the code:
# robot.rb
require 'open3'
Open3.popen3('ruby sum.rb') do |stdin, stdout, stderr, wait_thr|
while line = stdout.gets
if line == "Enter number A\n"
stdin.write("10\n")
elsif line == "Enter number B\n"
stdin.write("30\n")
else
puts line
end
end
end
robot.rb
failed to run. Seems it's stuck at sum.rb
's gets.chomp
.
Later I found out I have to write as following to make it work. You need to feed it with inputs before hand and in right sequence.
# robot_2.rb
require 'open3'
Open3.popen3('ruby sum.rb') do |stdin, stdout, stderr, wait_thr|
stdin.write("10\n")
stdin.write("30\n")
puts stdout.read
end
What confused me are:
robot_2.rb
is not like interact with shell, it's more like feed what the shell needs, cause I just know. What if a program needs many inputs and we cannot predict the order?I found out if
STDOUT.flush
been added after eachputs
insum.rb
,robot.rb
could run. But in reality we cannot trustsum.rb
's author could addSTDOUT.flush
, right?
Thanks for your time!