开发者

ruby loop to class problem

开发者 https://www.devze.com 2023-01-07 08:36 出处:网络
ok, easier to read version of the code (I hope) class First attr_accessor :addresses def initialize address

ok, easier to read version of the code (I hope)

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=F开发者_如何学运维irst.new

  email_servers=[Server1.new,Server2.new]

  def loopaddress
  n.addresses.each_with_index do |i|
            i % email_servers.length
          end

  end

end

Just trying to make the looped addresses be distributed uniquely one at a time between both servers. Thanks


This algorithm ought to work:

#!/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

Edited to add: I wouldn't create more classes just because "classes are good, m'kay?" I'd do it because, for example, a method takes an object as its argument and operates repeatedly on that object; that method probably ought to be moved to that object. That said, addresses could possibly stand to be its own object:

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

精彩评论

暂无评论...
验证码 换一张
取 消