将“应用程序数据”与现有IO对象相关联

时间:2014-05-29 06:42:59

标签: ruby

我上课了:

class MyProgram
    attr_reader :control_socket

    def initialize
        @control_socket = UNIXSocket.new('path/to/socket')
        ...
    end

    def read_message
        ...
    end
end

我想选择该程序的多个实例,如下所示:

# Does not work
programs = [my_pgm1, my_pgm2]
io_wrappers = programs.collect { |p| wrap(p) }
r, w, err = select(programs)
r.each { |pgm|
    pgm.my_program.read_message
}

我想知道是否有办法将UNIXSocket包装起来将MyProgram与之关联起来。

1 个答案:

答案 0 :(得分:0)

如何将套接字中的地图保留回各自的程序?

programs = [my_pgm1, my_pgm2]
sockets = Hash[programs.map { |p| [p.control_socket, p] }
r, w, err = select(sockets.keys)
r.each { |socket|
    sockets[socket].read_message
}

<强>更新

我没有对此进行测试,但您可以尝试创建一个显式转换:

class MyProgram
  def to_io
    control_socket
  end
end

programs = [my_pgm1, my_pgm2]
r, w, err = select(programs)
r.each { |pgm|
    pgm.read_message
}