Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby readline fails if process started with arguments

Tags:

ruby

I'm having the strangest issue. This code below works fine:

require 'json'
require 'net/http'
h = Net::HTTP.new("localhost", 4567) 
while(l = gets.chomp!)
   res = h.post("/api/v1/service/general",l)
   puts res.body
end

However, with the small modification of getting host/port from parameters:

require 'json'
require 'net/http'
h = Net::HTTP.new(ARGV[0], ARGV[1]) 
while(l = gets.chomp!)
   res = h.post("/api/v1/service/general",l)
   puts res.body
end

..and starting with ruby service.rb localhost 4567 ...

I get this error:

service.rb:4:in `gets': No such file or directory - localhost (Errno::ENOENT)

Using ruby 1.9.2p0 on Ubuntu 11.04

like image 820
mikabytes Avatar asked Aug 06 '11 09:08

mikabytes


2 Answers

Have you tried while (l = $stdin.gets.chomp!)? Otherwise Kernel#gets reads from ARGV.

like image 117
Michael Kohl Avatar answered Oct 19 '22 01:10

Michael Kohl


Try it like this:

h = Net::HTTP.new(ARGV.shift, ARGV.shift) 
while(l = gets.chomp!)

It will still fail if you pass in more than two arguments. You should call ARGV.clear after constructing h if you want to deal with that.

like image 1
Mat Avatar answered Oct 19 '22 01:10

Mat