好的,更容易阅读代码版本(我希望)
class First
attr_accessor :addresses
def initialize
address
end
def address
@addresses= []
File.open("/RubyDev/useful/lib/list/listtest.txt").each_line do |i|
@addresses << i.chomp
end
end
end
class Server1
b = Last.new
puts "Im Server1"
puts "Sending the following address to: #{b.loopaddress}"
end
class Server2
b = Last.new.loopaddress
puts "Im Server2"
puts "Sending the following address to: #{b.loopaddress}"
end
class Last
n=First.new
email_servers=[Server1.new,Server2.new]
def loopaddress
n.addresses.each_with_index do |i|
i % email_servers.length
end
end
end
只是尝试在两台服务器之间一次一个地分配循环地址。感谢
答案 0 :(得分:1)
这个算法应该有效:
#!/usr/bin/ruby1.8
addresses = (1..10).to_a # Your list of addresses goes here
servers = (1..2).to_a # Your list of servers goes here
addresses.each.with_index do |address, i|
server = servers[i % servers.length]
puts "Sending address #{address} to server #{server}"
end
# => Sending address 1 to server 1
# => Sending address 2 to server 2
# => Sending address 3 to server 1
# => Sending address 4 to server 2
# => Sending address 5 to server 1
# => Sending address 6 to server 2
# => Sending address 7 to server 1
# => Sending address 8 to server 2
# => Sending address 9 to server 1
# => Sending address 10 to server 2
编辑补充说:我不会因为“课程很好,m'kay而创建更多课程”。我这样做是因为,例如,一个方法将一个对象作为其参数并在该对象上重复操作;该方法可能应该移动到该对象。也就是说,地址可能是它自己的对象:
class Addresses
def initialize
@addresses = (1..10).to_a # Or read from a file, or whatever
end
def send_to_servers(servers)
@addresses.each.with_index do |address, i|
server = servers[i % servers.length]
puts "Sending address #{address} to server #{server}"
end
end
end
servers = (1..2).to_a # Your list of servers goes here
addresses = Addresses.new
addresses.send_to_servers(servers)