在Ruby中将eventmachine输出返回给对象

时间:2013-04-17 17:27:49

标签: ruby eventmachine

在下面的函数(在类Myclass中定义)中,我可以像ruby一样运行函数

myoutput =  Myclass.get_par("http://eol.org/api/ping/1.0.json,http://eol.org/api/ping/1.0.json")

并且调用的输出被打印到终端,但是输出分配给对象myoutput

有没有办法让输出返回到一个对象,而不仅仅是打印?

def self.get_par(urls)
  allurls = urls.split(',')
  results = []
  EM.synchrony do
    concurrency = 2
    results << EM::Synchrony::Iterator.new(allurls, concurrency).map do |url, iter|
      http = EventMachine::HttpRequest.new(url).aget
      http.callback { iter.return(http.response) }
      http.errback { iter.return(http) }
    end
    EventMachine.stop
    puts results # all completed requests
  end
end

2 个答案:

答案 0 :(得分:0)

puts会返回nil,因此返回puts的结果对您没有太大帮助。

返回results,或同时返回两者,例如

def self.get_par(urls)
  # ... etc ...
  puts results
  results
end

答案 1 :(得分:0)

原来我只是在错误的地方返回输出

def self.get_par(urls)
  allurls = urls.split(',')
  results = []
  EM.synchrony do
    concurrency = 2
    results << EM::Synchrony::Iterator.new(allurls, concurrency).map do |url, iter|
      http = EventMachine::HttpRequest.new(url).aget
      http.callback { iter.return(http.response) }
      http.errback { iter.return(http) }
    end
    EventMachine.stop
  end
  results # SHOULD HAVE BEEN HERE #
end