2010-07-14 86 views
-1

OK,更容易閱讀的代碼版本(我希望)紅寶石環路類問題

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 

只是想使循環地址可以在兩個服務器之間的時間唯一一個分佈。由於

+1

'each_with_index'中的塊接收_two_參數,元素及其索引。 – 2010-07-14 18:47:32

+0

謝謝,很高興知道 – rahrahruby 2010-07-14 21:03:20

回答

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) 
+0

感謝wayne,你可以把服務器和地址放在課堂上嗎?那就是我有掛斷。 – rahrahruby 2010-07-14 20:54:01

+0

非常感謝。我很欣賞你的回答以及你製作它的時間。 – rahrahruby 2010-07-14 21:51:35

+0

@MAP,這是我的榮幸! – 2010-07-14 22:43:30