On Jul 18, 2008, at 10:03 AM, Matthew Moss wrote:

> ## Records and Arrays (#170)



cfp:~ > cat quiz-170.rb
#
# quiz-170.rb
#

aor = [ Record[0,1,2], Record[3,4,5], Record[6,7,8] ]

y 'aor'                                   => aor
y 'aor2roa(aor)'                  => aor2roa(aor)
y 'roa2aor(aor2roa(aor))' => roa2aor(aor2roa(aor))




BEGIN {

   require 'yaml'
   require 'rubygems'
   require 'arrayfields'

   class Record < Array.struct(%w( a b c ))
     def to_yaml(*a, &b) to_hash.to_yaml(*a, &b) end
   end

   module Inline
     def to_yaml_style() :inline end
   end

   Array.send :include, Inline
   Record.send :include, Inline

   def aor2roa aor
     fields = aor.first.fields
     rclass = aor.first.class
     roa    = rclass[]
     aor.each do |record|
       fields.each do |field|
         (roa[field] ||= [] ) << record[field]
       end
     end
     roa
   end

   def roa2aor roa
     fields = roa.fields
     rclass = roa.class
     aor    = []
     n      = fields.map{|field| roa[field].size}.max
     n.times do |i|
       values = fields.map{|field| roa[field][i]}
       aor << rclass[*values]
     end
     aor
   end

}



cfp:~ > ruby quiz-170.rb
---
aor: [{a: 0, b: 1, c: 2}, {a: 3, b: 4, c: 5}, {a: 6, b: 7, c: 8}]
---
aor2roa(aor):
   a: [0, 3, 6]
   b: [1, 4, 7]
   c: [2, 5, 8]
---
roa2aor(aor2roa(aor)): [{a: 0, b: 1, c: 2}, {a: 3, b: 4, c: 5}, {a: 6,  
b: 7, c: 8}]




a @ http://codeforpeople.com/
--
we can deny everything, except that we have the possibility of being  
better. simply reflect on that.
h.h. the 14th dalai lama