Nice way to break a reply up into pieces in ruby

Posted by ChaosR on Stack Overflow See other posts from Stack Overflow or by ChaosR
Published on 2010-02-04T10:36:32Z Indexed on 2010/04/04 17:03 UTC
Read the original article Hit count: 196

Hello, I'm writing an IRCd. For this topic it doesn't really matter if you know much about IRC. Its a simple code style problem.

Quick overview of the problem:

  • No message may be longer than 512 characters
  • If the message is more, it must be broken into pieces
  • The NAMES reply sends all the nicknames of users on a channel, and quickly grows beyond 512 characters.

I currently concocted this marvelous piece of code, it works perfectly. However, its just not "ruby-like". This piece of code is more what you expect in some piece of C code.

# 11 is the number of all fixed characters combined in the reply
pre_length = 11 + servername.length + mynick.length + channel.name.length
list = [""]
i = 0
channel.nicks.each do |nick, client|
  list[i+=1] = "" if list[i].length + nick.length + pre_length > 500
  list[i] << "#{channel.mode_char(client)}#{client.nick} "
end
list.each { |l| send_numeric(RPL_NAMREPLY, channel.name, l.strip) }
send_numeric(RPL_ENDOFNAMES, channel.name)

So my question is, any ideas to do this more nicely?

PS. code has been slightly modified to make it easier to understand out-of-context

© Stack Overflow or respective owner

Related posts about ruby

Related posts about coding-style