Refering to an object's 'parent'

T

Toby Rodwell

I'd like to check an object's "parent" to see if it has a certain
method, so for example, given ...

class House(type)
attr_accessor :rooms, :type_of_house
@rooms = []
...
def type_of_house
type
end
end

class Room
...
end

my_room = Room.new

my_house = House.new

my_house.rooms.push(my_room)

... then is it somehow possible to ask ...
my_room.<PARENT>.respond_to?(type_of_house) ?
(I know 'House' is not really the parent of 'Room', and so I suspect the
answer is "no", but it can't hurt to ask. Thanks.
 
B

Bill Siggelkow

What I suggest is that you add an attribute to Room that holds a
reference to the house; then you can set that reference either when
you instantiate the Room or when you push it onto the array ...

-Bill
http://billonrails.blogspot.com
 
A

ara.t.howard

class House(type)
attr_accessor :rooms, :type_of_house
@rooms = []
...
def type_of_house
type
end
end

class Room
...
end

my_room = Room.new

my_house = House.new

my_house.rooms.push(my_room)

... then is it somehow possible to ask ...
my_room.<PARENT>.respond_to?(type_of_house) ?
(I know 'House' is not really the parent of 'Room', and so I
suspect the
answer is "no", but it can't hurt to ask. Thanks.

sure.

cfp:~ > cat a.rb
class House
attr_accessor :rooms, :type_of_house

def initialize
@rooms = Room::List.new self
end

def type_of_house
type
end

class Room
attr_accessor :parent

class List < ::Array
attr_accessor :house
def initialize house
@house = house
end
def push room
super
ensure
room.parent = house
end
end
end
end

my_room = House::Room.new

my_house = House.new

my_house.rooms.push(my_room)

p my_room.parent.respond_to?:)type_of_house)

cfp:~ > ruby a.rb
true


probably better design to make a room factory for house though:

cfp:~ > cat a.rb
class House
attr_accessor :rooms, :type_of_house

def initialize
@rooms = []
end

def type_of_house
type
end

def new_room
rooms.push(Room.new(self)).last
end

class Room
attr_accessor :house

def initialize house
@house = house
end
end
end


my_house = House.new

my_room = my_house.new_room

p my_room.house.respond_to?:)type_of_house)

cfp:~ > ruby a.rb
true



kind regards.



a @ http://codeforpeople.com/
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top