简体   繁体   English

从脚本Ruby中创建对象

[英]Create an object from within a script Ruby

I am attemping to create an object from a class. 我试图从一个类创建一个对象。 But the objects will be created when they are needed.. Code below a bit hard to explain 但是对象将在需要时创建。.下面的代码有点难以解释

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)

Now I can't do that Becuase incoming_message is not a constant. 现在,我无法执行此操作,因为传入的消息不是一个常量。 How would I get around this? 我该如何解决?

EDIT: 编辑:

To clear things up a bit. 整理一下。 I do need to use this class to create multiple objects with diffrent names. 我确实需要使用此类来创建具有不同名称的多个对象。 The repeater is for a chat server where an incoming message from 1 user is taken in then sent back out all of the clients connected. 转发器用于聊天服务器,其中接收来自1个用户的传入消息,然后将其发送回所有连接的客户端。 Each new client that connects would have a object created with that specific IP address so that messages from others can be send to the client. 每个连接的新客户端都会有一个使用该特定IP地址创建的对象,以便可以将来自其他客户端的消息发送到该客户端。

It would take in messages from the other users by everyone sending to the server on the same port read the message then write to clients what it received... 发送到同一端口上的服务器的每个人都会从其他用户那里接收消息,然后读取消息,然后将收到的消息写给客户端...

I hope this helped sorry for all the confusion :) 我希望这对所有的困惑有所帮助:)

If you want to maintain some kind of global class-level state, you should define a class-level accessor on Repeater that you can assign your repeating message to. 如果要维护某种全局的类级别状态,则应在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)

You need to use some parsing + serialization . 您需要使用一些解析+序列化。 Can they wire an already serialized/marshalled string? 他们可以连接已经序列化/编组的字符串吗?

1) convert the ruby code to yaml or json
2) use the json or yaml load method like myobj = YAML.load(new_yaml_string)

or 要么

save it in another file called input and do a 
require 'input'
create object of repeater

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM