From: "Ara.T.Howard" Date: 2003-11-19T04:27:20+09:00 Subject: Re: testing argument type and duck typing, newbie question On Tue, 18 Nov 2003, Raphael Bauduin wrote: > I use them as a key to extract an element from a Hash (if arg is a string) > or from a Array (if arg is an integer). i do things like this alot too. in my experience it is easiest to do this with an object rather than in a procedural way. i don't know your exact setup, but it sounds like you are probably tracking things by key and position so you can maintain an ordered hash (otherwise you'd simply be hashing on int or string). why not simply create a class to do the work? you can put all the code in one place and even write a unit test for the class. something like class LookUpTable < Hash def ary; @ary ||= []; end def [] k; (Numeric === k ? ary : self)[k]; end def []= k,v; ary << super; end end lut = LookUpTable.new keys = :a, :b, :c keys.each{|k| lut[k] = k.to_s} p lut lut.size.times{|i| printf "lut[%d] => %s\n", i, lut[i]} __END__ {:b=>"b", :a=>"a", :c=>"c"} lut[0] => a lut[1] => b lut[2] => c this may not be your exact case but my point is simply this: if you are going impliment a lookup based on key type, why not build a class that does a lookup based on key type? this way the key checking can be done in one place. it's so easy to crank out classes in ruby that i do it anytime i'm associating methods with data. regards. -a -- ATTN: please update your address books with address below! =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | STP :: http://www.ngdc.noaa.gov/stp/ | NGDC :: http://www.ngdc.noaa.gov/ | NESDIS :: http://www.nesdis.noaa.gov/ | NOAA :: http://www.noaa.gov/ | US DOC :: http://www.commerce.gov/ | | The difference between art and science is that science is what we | understand well enough to explain to a computer. | Art is everything else. | -- Donald Knuth, "Discover" | | /bin/sh -c 'for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done' ===============================================================================