From: David Alan Black Date: 2002-05-04T12:26:24+09:00 Subject: Re: ruby idiom check Hello -- On Sat, 4 May 2002, Mark Probert wrote: > > I have a class that telnets into a number of different > systems. Each of these systems has it own set of defaults > such as ports, address, username, and so on. > > The thought I had to abstract this was (1) to sub-class > or (2) to use Struct to contain the differences, a la: > > > SysDefs = Struct::new(:name, :val) > > $OneDef = SysDefs::new('type 1', 123) > $TwoDef = SysDefs::new('type 2', 234) > > class BasicSys > attr_reader :name, :val, :stuff > > def initialize(key=1) > @def = SysDefs::new > case key > when 1 > @def = $OneDef > when 2 > @def = $TwoDef > end > @name = @def.name > @val = @def.val > @stuff = nil > end > end > > Any thoughts as to which is the preferred design choice > and why? I would tend to want to get rid of the global variables, and also to confine the knowledge of the hash keys to as small a space as possible. Here's an example of this (probably not optimal, but anyway). The SysDefs module contains one method which knows about the names of the keys, and one method which returns a hash based on a key. I've also done some other things differently, just for fun -- for example, instead of assigning :name and :val values to @name and @value, I've just made BasicSys inherit from Hash. (This may or may not make sense for your actual application.) module SysDefs def defs default = ["type 1", 123] defs = [ default, ["type 2", 234] ] end def get_def(key) spec = defs.detect{ |d| /#{key}/.match(d[0]) } Hash[:name => spec[0], :val => spec[1]] end end class BasicSys < Hash include SysDefs def initialize(*key) replace get_def(key) end end # Mini-test: p BasicSys.new # => {:val=>123, :name=>"type 1"} p BasicSys.new(2) # => {:val=>234, :name=>"type 2"} David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav