From: Leslie Viljoen Date: 2005-11-24T05:31:33+09:00 Subject: Re: How does this work? Gavin Kistner wrote: > On Nov 23, 2005, at 10:42 AM, Graham wrote: > >> I cam across a construct in the FXRuby examples which I've not seen >> before.. >> ..... lots of constants..(about 47 in total I believe) >> ID_INSERT_FILE, >> ID_EXTRACT_FILE, >> ID_WHEELADJUST, >> ID_LAST = enum(FXMainWindow::ID_LAST, 47) >> >> and I'm assuming this generates a unique number for each piece of text, >> which is subsequently used in the rest of the code. How does it work? > > > Just a guess: > > def enum( start, count ) > (start...start+count).to_a > end > > a,b,c = enum( 101, 3 ) > p a,b,c > #=> 101 > #=> 102 > #=> 103 > > > Except it looks like it's using the last value to update a constant > for future calls: > > LAST_ID = 101 > def enum( start, count ) > return (start...start+count).to_a > end > > a,b,c,LAST_ID = enum( LAST_ID, 4 ) > p a,b,c > #=> 101 > #=> 102 > #=> 103 > > d,e,f,g,LAST_ID = enum( LAST_ID, 5 ) > p d,e,f,g > #=> 104 > #=> 105 > #=> 106 > #=> 107 > > > Note that the above (properly) generates warnings each time you > reassign to the global value. IMO a proper 'enum' solution would keep > track of that value internally. > > Like so?: #!/usr/bin/env ruby module Enum @@last = 0 def enum(n) r = (@@last..(@@last+n-1)).to_a @@last += n r end end include Enum ROBO_LTHRUST, ROBO_RTHRUST, ROBO_FIRE = enum(3) p ROBO_LTHRUST, ROBO_RTHRUST, ROBO_FIRE