Forum: Ruby How does this work?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
gandalfmeister (Guest)
on 2005-11-23 17:46
(Received via mailing list)
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
gavin (Guest)
on 2005-11-23 17:58
(Received via mailing list)
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.
fghfghfh (Guest)
on 2005-11-23 20:19
(Received via mailing list)
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
leslie (Guest)
on 2005-11-23 22:33
(Received via mailing list)
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
This topic is locked and can not be replied to.