Ruby OO-newbie design-question

Hi!
I’m not at all new to programming, I know OO-concepts but I don’t have any
hands-on experience with designing/programming OO except for small tests.
I’m also a Ruby newbie, but have been coding a LOT of C, (advanced)
Shellscripts and Python.

I need advice on good design, taking features of Ruby into consideration.

I want a tree of objects like this:

a1
b1
c1
b2
c1
c2
d1

and so on… The a#-objects will hold default values and methods for b# and
b# will hold default values for c# and so on. When a value in a# is changed
I want its children to immediatly inherit them also, if they aren’t
overridden. b# will be subclasses of a#, c# will be subclasses of b# etc.
I have to be able to dynamically (at runtime) add and delete children.

What is a good way to design this with the OO-features of Ruby, keeping it
as readable and clean as possible?

Regards,
Per Wigren

Hi Per,

Unless a, b, and c have different behavior (not just values), I think you
can do it with a single class:

class Node
include Enumerable

def initialize
    @parent = nil
    @children = []
    @values = {}
end

def each(&b)
    @children.each &b
end

def add_child(child)
    child.parent = self
    @children << child
end

def remove_child(child)
    child.parent = nil
    @children.delete(child)
end

def [](key)
    # if the value exists locally, return it; otherwise, if parent

exists, ask it
@values[key] or (@parent and @parent[key])
end

def []=(key, value)
    @values[key] = value
end

protected

def parent=(parent)
    @parent = parent
end

end

Then you can do this:

a1 = Node.new
b1 = Node.new
a1.add_child(b1)
c1 = Node.new
b1.add_child(c1)
b2 = Node.new
a1.add_child(b2)

and so on…

a1[‘color’] = ‘purple’
b1[‘color’] = ‘yellow’
puts b2[‘color’] # ‘purple’
puts c1[‘color’] # ‘yellow’
puts c1[‘nothing’] # nil

Is that what you had in mind?

“Per Wigren” wigren@home.se wrote in message news:3f4f3875_2@127.0.0.1

Hi!
I’m not at all new to programming, I know OO-concepts but I don’t have any
hands-on experience with designing/programming OO except for small tests.
I’m also a Ruby newbie, but have been coding a LOT of C, (advanced)
Shellscripts and Python.

I need advice on good design, taking features of Ruby into consideration.

I want a tree of objects like this:

a1
b1
c1
b2
c1
c2
d1

and so on… The a#-objects will hold default values and methods for b#
and
b# will hold default values for c# and so on. When a value in a# is
changed

···

I want its children to immediatly inherit them also, if they aren’t
overridden. b# will be subclasses of a#, c# will be subclasses of b# etc.
I have to be able to dynamically (at runtime) add and delete children.

What is a good way to design this with the OO-features of Ruby, keeping it
as readable and clean as possible?

Regards,
Per Wigren