inheriting constants

A

Ara.T.Howard

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 :: http://www.ngdc.noaa.gov/stp/
| TRY :: for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done
===============================================================================
 
R

Robert Klemme

Ara.T.Howard said:
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

:)

robert
 
J

Joel VanderWerf

Ara.T.Howard said:
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 :eek:ptions

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.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,108
Latest member
AlbertEste
Top