Ruby noob在这里。任何有关我所遇到的小问题的帮助都将不胜感激。 我试图将数组放入一个连接字符串参数,格式为数组。
我的数组如下:
hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
我需要将数组拆开并将其构造成数组,以便我可以立即将所有连接替换为调用。主机数量可能会有所不同,因此为什么它在数组中。
hosts_mapped = hosts.map { |i| "'" + i.to_s + "'" }.join(",")
给了我“192.168.0.2:27017","192.168.0.3:27017”字符串我认为......或者这可能已经将它映射回数组,因为我得到的错误看起来像下面的那个试图建立连接。
@conn = Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync, :refresh_interval => 10)
Exception `Mongo::ConnectionFailure' at gems/mongo-1.7.0/lib/mongo/util/pool_manager.rb:282 - Cannot connect to a replica set using seeds '192.168.0.2:27017
Mongo::ConnectionFailure: Cannot connect to a replica set using seeds '192.168.0.2:27017
正如您所看到的,它似乎只是引用了第一个条目。我需要在配置文件中保存此数组,因此这不是直接进入上面的连接字符串的原因。 对我而言,似乎我已将hosts_mapped映射回一个数组,但如果我放置hosts_mapped,我会以正确的格式获取字符串。
"192.168.0.2:27017","192.168.0.3:27017"
工作连接字符串如下所示:
@conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10)
有谁知道我在哪里错了?
要测试的完整代码:
#!/usr/bin/ruby -d
require "mongo"
hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
hosts_mapped = hosts.map {|i| "'" + i.to_s + "'" }.join(",") @conn =
Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync,:refresh_interval => 10)
答案 0 :(得分:0)
根据文档Mongo::ReplSetConnection.new
可以采用数组:
Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'])
由于你已经拥有一个数组,你可以将它作为第一个参数传递:
hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
Mongo::ReplSetConnection.new(hosts)
答案 1 :(得分:0)
你已经有一个数组hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
如果@conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10)
有效,那么您需要做的就是
@conn = Mongo::ReplSetConnection.new(hosts, :refresh_mode => :sync, :refresh_interval => 10)