What a fantastic module!

Every once in a while I get to know a bit more of Ruby and I feel the joy which Matz talks about!

From: The Philosophy of Ruby

For me the purpose of life is partly to have joy. Programmers often feel joy when they can concentrate on the creative side of programming, So Ruby is designed to make programmers happy.

Today I was looking for executing a program from within Ruby. Now this program takes command line input and gives some output as well. So, I went around trying the usual %x(program.rb) but obviously that didn’t work.

Finally I came across Open3 which is a core module of Ruby!

So, you can write a program like this (like one of the programs you learn right in the beginning) –

#! name.rb
name = gets.chomp
puts "Hello #{name}"

And then use Open3 to execute it!

#! program.rb
require 'open3'

Open3.popen3("ruby name.rb") do |stdin, stdout, stderr, thread|
  stdin.write("Abhijit\n")
  puts stdout.read.chomp
end

Cool!!

Can this be used to login to the shell as another user? Maybe, but there are better ways of doing it!