From: John W Higgins Date: 2009-09-16T07:41:02+09:00 Subject: Re: Array of Hashes in an array of hashes - Complicated! --0016363107cdfafb9d0473a579ff Content-Type: text/plain; charset=ISO-8859-1 Matt, On Tue, Sep 15, 2009 at 2:44 PM, Matt Brooks wrote: > I have to figure out how to make a Signal Object, i can't see how I am > going to get around having this messed up hash problem even if I make a > signal object. because of the repeating fields within the data. > class Signal .... end x = Signal.new > > I think having objects only changes the fact of instead of having an > array of hashes at my top level, i have an array of objects that have > hashes inside of them anyway... I have hundreds of variables for each > signal, and I can't make this signal object have 200 local variables, I > think it would be dirty to type > attr_reader: for all the hundreds variables... > It's difficult to come up with suggestions if we only have partial information - you never mentioned that you had 200 or so possible variables for these items - not bitching - it's just difficult to be of assistance when one thinks you are looking at 4-5 variables and suddenly it grows 50 times. The first advantage of the object is that you can approach things one piece at a time and get better control over each piece - everything is well defined and you aren't dealing with as many abstract concepts as arrays of hash of arrays....... So what you appear to have is the following - a single Signal has hundreds of variables of which some of them have multiple values for the same Signal. Lets start piecing together a class then (no ruby available so this might not work exactly as typed. (Gist located here http://gist.github.com/187725) class SignalVariable attr_reader :value def add(val) #we switch from a raw string to an array if this is the second time we've added if @value #add the new value to the array #it looks strange but it doesn't matter how many times you have added an item #it's easier then an if x then y else z concept to me @value = [@value, val].flatten else @value = val end end end class Signal def initialize() #setup the hash and have it create the variable object for every new item @variables = Hash.new{ |h,k| h[k] = SignalVariable.new } end def add_variable(name, value) @variables[name].add(value) end def method_missing(name, *args) #this will allow a call to Signal.xxx to return xxx automatically #no need to define every variable return @variables[name].value if @variables.key?(name) super end end This would allow you to just enter each variable as you came to it - regardless of whether it was repeated or not. The return values would be either the value or an array of values depending on whether or not something was repeated. I'm sure some folks will think this is a foolish option - it's just the way I would approach it...... John --0016363107cdfafb9d0473a579ff--