How does this work?


#1

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?

Graham


#2

On Nov 23, 2005, at 10:42 AM, Graham wrote:

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.


#3

Gavin K. wrote:

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.
Doesn’t if you do

Enumeration

def enum(start, count)
(start…(start+count)).to_a
end
as (start+count) is only evaluated once I assume.

Thanks for the clarification, once I realised it was just an FX specific
method, and not some cool use of the Enumeration class it sort of fell
into place.
Cheers
Graham


#4

Gavin K. wrote:

and I’m assuming this generates a unique number for each piece of text,
p a,b,c
return (start…start+count).to_a
#=> 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