0

到目前为止的代码:

def queryConnect
    ...
    count = 0

    #clients is an array of hashes.
    #channels is an array of hashes.

    channel_array = []

    channels.each do |channel|
        begin
            if clients[count]["cid"].to_i == channel["cid"].to_i
                channel_array << { "cname" => channel["channel_name"].transform_escape, 
                                   "name"  => clients[count]["client_nickname"].transform_escape }
                count = count + 1
            else
                channel_array << { "cname" => channel["channel_name"].transform_escape }
            end
        rescue
            #transform_escape -> some elements are not type string.
        end
    end
    count = 0
    channel_array
end

通道样本输入:[{"channel_name" => "game1", "cid" => 1}, {"channel_name" => "game2", "cid" => 2}, {"channel_name" => "game3", "cid" => 3}]

客户样本输入:[{"client_nickname" => "greg", "cid" => 1}, {"client_nickname" => "bob", "cid" => 1}, {"client_nickname" => "george", "cid" => 3}]

预期输出:[{"cname" => "game1", "name" => ["greg", "bob"]}]

问题:我正在尝试遍历所有通道,如果客户端的通道 id 和通道的通道 id (cid) 匹配,我想使用通道名称和客户端名称创建一个哈希,然后将其推送到channel_array.

我现在唯一遇到的问题是当通道中有多个客户端时...如何通过迭代客户端数组并仍然保持条件以查看通道 ID 是否匹配来动态添加键值对?

两天来我一直在用我的文本编辑器来解决这个问题,感谢任何帮助。

4

2 回答 2

2
channels = [{"channel_name" => "game1", "cid" => 1}, 
            {"channel_name" => "game2", "cid" => 2}, 
            {"channel_name" => "game3", "cid" => 3}]
clients = [{"client_nickname" => "greg", "cid" => 1}, 
           {"client_nickname" => "bob", "cid" => 1}, 
           {"client_nickname" => "george", "cid" => 3}]

channel_data = channels.inject({}){|m, c| m[c["cid"]] = c["channel_name"]; m}
=> {1 => "game1", 2 => "game2", 3 => "game3"}

client_data = clients.inject({}){ |m, c| 
  m[c["cid"]] ||= []
  m[c["cid"]] << c["client_nickname"]
  m
}
=> { 1 => ["greg", "bob"], 3 => ["george"] }

channel_data.map{|cid, cname| 
  {"cname" => cname, "name" => client_data[cid]} if client_data[cid]
}.compact
=> [{"cname" => "game1", "name" => ["greg", "bob"]}, {"cname" => "game3", "name" => ["george"]}]
于 2013-04-19T04:24:54.327 回答
1

终于想通了。

channel_array << { "cname" => channel["channel_name"], "name" => clients.inject([]){ |m, c| m << c["client_nickname"] if c["cid"] == channel["cid"]; m} }
于 2013-04-19T13:53:54.537 回答