Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Nick Hennen
Nick Hennen
7,812 Points

Is there a way to pass a param from one completely separate ruby program to another on the same network and/or machine?

I am replacing existing programs with ruby little by little so as not break any existing functionality. The need for separate ruby programs may/ has arrived but I still need them to be able to interact with each other.

1 Answer

You've got a few options for this depending on your setup.

If both programs are running on the same machine and one will be executing the other you could simply pass command line parameters to the ruby script using the system method and ARGV. This can get quite fragile though so you may want to consider some other options.

You could also use low level sockets via the Socket class in the standard library.

server.rb
require 'socket'

server = TCPServer.new 2000 # Server bound to port 2000

loop do
  client = server.accept    # Wait for a client to connect
  client.puts "Hello !"
  client.puts "Time is #{Time.now}"
  client.close
end
client.rb
require 'socket'

s = TCPSocket.new 'localhost', 2000

while line = s.gets # Read lines from socket
  puts line         # and print them
end

s.close             # close socket when done

There are many other options including web services, messaging queues (e.g. resque or sidekiq), etc.