From: transfire@... Date: 2006-06-03T15:14:23+09:00 Subject: Re: An alternative to the class Foo < Struct.new(vars) idiom and SuperStruct ara.t.howard@noaa.gov wrote: > On Fri, 2 Jun 2006 transfire@gmail.com wrote: > > > > > Hal Fulton wrote: > >> That's another example of why I would like a data structure > >> that 1) had a convenient notation for literals and 2) was > >> "like" a Hash, but ordered. > > > > Facet's has Association which gives one something quite like that. > > > > [ :a >> 1, :b >> 2 ] > > > > Of course it does take over the #>> operator, so it can't be used > > inside any class that defines it. But that's not a big deal. It just > > means you can't _extend_ the following classes with code that uses an > > Association. > > > > Bignum > > Fixnum > > Date > > IPAddr > > Process::Status > > > > T. > > that just gave me an idea: > > harp:~ > cat a.rb > require 'arrayfields' > class Map < Array > class Pair < Array; end > def initialize *pairs > fields = [] > pairs.each{|k, v| self << v and fields << k} > self.fields = fields > end > def self.[](*a, &b) new(*a, &b) end > end > class Symbol > def >(value) Map::Pair[self, value] end > end > def Map(*a, &b) Map.new(*a, &b) end > def map(*a, &b) Map.new(*a, &b) end > > > m = map :a > 4, :b > 2 > p m > p m[:a] > p m[:b] > p m.to_hash > p m.keys > > > harp:~ > ruby -r rubygems a.rb > [4, 2] > 4 > 2 > {:b=>2, :a=>4} > [:a, :b] > > > what do you think? Cool. Pair is a lot like Association but you've added the Map class here. Of course you've limited yourself to symbol keys by using >. Using Associations does have some limitations as far as being a full fledged omap, since it's just an Array of Associations, but it would be easy enough to combine it with your map class. Put the two together and have: m = map :a>>4, :b>>2 Nice thing about Associations too is that have some other uses as well. The only thing that would be better is a literal form and perhaps a slighlty better operator. T.