From: Hal Fulton Date: 2006-01-06T18:56:37+09:00 Subject: Re: Attribute writers Michael Judge wrote: > I'm working on a survey system in Ruby and am having a style crisis with > a simple bit of code that has left me paralyzed and unable to work. > > Respondent data in research surveys is traditionally stored as big > strings of text like this: "123145992348241110111 11 11 1 1111 3331 1" > > This was a made up example, in the real world however, there's sometimes > hundreds of thousands of characters in each respondent's data string. > In the stats and analysis section of my program, I'm working out how to > access subsets of these strings in an object-oriented way. > > Something like this appeals to me and is very readable: > > if currentRespondent.ascii(0..2) == 123 > currentRespondent.ascii(0..2) = 777 > end > > How would one actually implement this? I'd suggest doing a little metaprogramming and making the final code a little easier. Here is a very rough outline -- if you like it I can help flesh out the details: class Respondent Fields = { :this => 0..2, :that => 3..6, :etc => 7..10 } Fields.each_pair do |field,range| # add a reader basically doing @resp[range] # add a writer basically doing @resp[range]=val end def initialize(str) @resp = str end end resp = Respondent.new(whatever) if resp.this == Something resp.this = SomethingElse end do_whatever if resp.that != resp.this Make sense? Hal