On Sep 26, 12:16 am, Jay Levitt <jay+n... / jay.fm> wrote:
> I had to write a script this evening to take an unsorted input file of the
> form:
>
> database 1 is on server 3
> database 8 is on server 7
> ...
>
> and output it in the form:
>
> server 3 handles database 1 through 7
> server 7 handles database 8 through 11
>
> My brain was in procedural mode, and I wrote the following ugliness:
>
> ---
>
> def output_range(start_db, end_db, server_n)
>    puts "server #{server_n} handles database #{start_db} through #{end_db}"
> end
>
> open("db_list.txt").readlines.each do |line|
>   m = line.match(/^database (.*) is on server (.*)/)
>   db_n = m[1].to_i
>   server_n = m[2].to_i
>
>   db_servers[db_n] = server_n
> end
>
> range_start = 1
>
> db_servers.each_index do |i|
>    next if i == 1
>      if db_servers[i] != db_servers[i - 1]
>        output_range(range_start, i - 1, db_servers[i - 1])
>        range_start = i
>    end
> end
>
> last_db = db_servers.size - 1
> output_range(range_start, last_db, db_servers[last_db])
> ---
>
> which in fact is not only horrid to look at, but has a bug (it doesn't like
> it if the input skips over a database number, i.e. db 233 and 235 are
> present but 234 is missing).

I'm not in the mood for hash.

ary = DATA.readlines
ary.map{|s| s[/\d+$/] }.uniq.each{|server|
  db = ary.grep(/ #{server}$/).map{|s|
    s[/\d+/].to_i}.sort
  puts "Server #{server} databases #{db[0]} to #{db[-1]}"
}

__END__
database 8 is on server 7
database 10 is on server 7
database 9 is on server 7
database 5 is on server 9
database 1 is on server 3
database 2 is on server 3
database 133 is on server 3
database 4 is on server 144