Inheriting constants

is this an appropriate way to inherit constants?

~/eg/ruby > cat a.rb
#!/usr/bin/env ruby

class A
OPTIONS = 1, 0

def klass; self.class; end

def options
opts =

k = klass
loop do
  opts.push(*k::OPTIONS)
  k = k.superclass 
  break unless defined?(k::OPTIONS)
end

opts

end
end

class B < A
OPTIONS = 3, 2
end

class C < B
OPTIONS = 5, 4
end

p A.new.options
p B.new.options
p C.new.options

~/eg/ruby > ruby a.rb
[1, 0]
[3, 2, 1, 0]
[5, 4, 3, 2, 1, 0]

-a

···

EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
PHONE :: 303.497.6469
ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328
URL :: Solar-Terrestrial Physics Data | NCEI
TRY :: for l in ruby perl;do $l -e “print "\x3a\x2d\x29\x0a"”;done
===============================================================================

“Ara.T.Howard” Ara.T.Howard@noaa.gov schrieb im Newsbeitrag
news:Pine.LNX.4.44.0402191548060.8595-100000@fattire.ngdc.noaa.gov

is this an appropriate way to inherit constants?

Looks ok to me. It’s just that I don’t like unnecessary “breaks” of loops
which is why I’d define options() like this:

def options
opts =
k = self.class

while k && defined?(k::OPTIONS)
  opts.concat(k::OPTIONS)
  k = k.superclass
end

opts

end

:slight_smile:

robert

Ara.T.Howard wrote:

is this an appropriate way to inherit constants?

You are organizing your options as a set, but if you are interested in a
hash model, you might be interested in a “class_superhash”, which is
sort of a hash that inherits key-value pairs according to the class
hierarchy. F’rexample:

require ‘superhash’

class A
class_superhash :options

options[:foo] = 1

def options; self.class.options; end
end

class B < A
options[:bar] = 2
end

p A.options
p B.options.to_hash
p B.new.options.to_hash

Output:

{:foo=>1}

{:foo=>1, :bar=>2}

{:foo=>1, :bar=>2}

The underlying superhash objects support the same interface as a hash.
(This is in my superhash package on RAA.)