[英]Create an object from within a script Ruby
我试图从一个类创建一个对象。 但是对象将在需要时创建。.下面的代码有点难以解释
incoming_message = #message sent though inter webs
class Repeater
def initialize(username, ip)
#repeat incoming message to back to ip
end
end
incoming_message = Repeater.new(user, ip)
现在,我无法执行此操作,因为传入的消息不是一个常量。 我该如何解决?
编辑:
整理一下。 我确实需要使用此类来创建具有不同名称的多个对象。 转发器用于聊天服务器,其中接收来自1个用户的传入消息,然后将其发送回所有连接的客户端。 每个连接的新客户端都会有一个使用该特定IP地址创建的对象,以便可以将来自其他客户端的消息发送到该客户端。
发送到同一端口上的服务器的每个人都会从其他用户那里接收消息,然后读取消息,然后将收到的消息写给客户端...
我希望这对所有的困惑有所帮助:)
如果要维护某种全局的类级别状态,则应在Repeater
上定义一个类级别访问Repeater
,您可以将重复消息分配给该类访问Repeater
。
class Repeater
class << self
attr_accessor :incoming_message
end
def initialize(username, ip)
# repeat Repeater.incoming_message to back to ip
end
end
Repeater.incoming_message = "what"
Repeater.new(user, ip)
您需要使用一些解析+序列化。 他们可以连接已经序列化/编组的字符串吗?
1) convert the ruby code to yaml or json
2) use the json or yaml load method like myobj = YAML.load(new_yaml_string)
要么
save it in another file called input and do a
require 'input'
create object of repeater
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.