首页 文章

从Ruby方法中抑制nil响应

提问于
浏览
0

我的任务是修改现有的Ruby脚本,但我的Ruby知识最基本......我需要添加一个方法来检查服务器的端口是否打开 . 如果是,脚本应该继续做它正在做的事情 . 如果没有,它应该退出 .

我已经应用了以下方法,取自Ruby - See if a port is open

def is_port_open?
  @host = "localhost"
  @port = "8080"
  begin
    Timeout::timeout(1) do
      begin
        s = TCPSocket.new(@host, @port)
        s.close
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return "port closed :("
      end
    end
  rescue Timeout::Error
  end
  return "problem with timeout?"
end

这种方法似乎运行良好,除非在端口打开时返回“nil” . 如何抑制任何输出(除非出现错误)?

提前致谢!

1 回答

  • 1

    您是否只需要检查条件(端口是否打开):

    require 'timeout'
    require 'socket'
    
    def is_port_open? host, port
      @host = host || "localhost"
      @port = port || "8080"
      begin
        Timeout::timeout(1) do
          begin
            s = TCPSocket.new(@host, @port)
            s.close
            return true # success
          rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
            return false # socket error 
          end 
        end 
      rescue Timeout::Error
      end 
      return false # timeout error
    end
    
    is_port_open? 'localhost', 8080
    #⇒ true
    is_port_open? 'localhost', 11111
    #⇒ false
    

    现在由您决定在出现错误等情况下返回什么 . 请注意,另一个选项是让异常传播给调用者 . 此函数会更短,但您需要在调用者中处理异常 .

相关问题