ruby_le ruby_le - 8 days ago 6
Ruby Question

How do I store standard outputs to multiple variables?

How do I store Ruby standard outputs to multiple variables?

For example, if I have:

puts "hello"

puts "thanks"


How do I store "hello" and "thanks" to two different variables like
strVar
(containing the value "hello") and
strVar2
(containing the value "thanks").

In my script, I am calling another Ruby script which will
puts
multiple strings to standard output. How do I store each string from the standard output individually?

Answer

You're basically chaining applications/scripts together. There are multiple ways to do it but the simplest path uses the STDIN/STDOUT pipeline.

A simple example would be using two small scripts. Save this as test.rb:

puts 'foo'
puts 'bar'

and this as test2.rb:

v1 = gets.chomp
v2 = gets.chomp

puts "v1=#{v1} v2=#{v2}"

then, at the command line use:

ruby test.rb | ruby test2.rb

which will output:

v1=foo v2=bar

| is how we chain the output of one script to the input of another and isn't part of Ruby, it's part of the OS.

This works because, by default, puts writes to STDOUT and gets reads from STDIN. | wires them together.