I am trying to write a Person class in Ruby which has some methods and properties. The below is how I have implemented it now.
class Person
attr_accessor :name, :gender, :mother
def initialize(name, gender, mother)
@name = name
@gender = gender
@mother = mother
@spouse = nil
end
def add_spouse(spouse)
if spouse
@spouse = spouse
spouse.spouse = self
end
end
def father(self)
return [self.mother.spouse]
end
end
I want to access the methods like this:
m = Person.new('mom', 'Female')
d = Person.new('dad', 'Male')
d.add_spouse(m)
p = Person.new('Jack', 'Male', m)
If I want to get the father of p, then I want to get it like this: p.father.
So is the above implementation correct?
I am getting the below error if I run the code:
person.rb:18: syntax error, unexpected `self', expecting ')'
def father(self)
person.rb:21: syntax error, unexpected `end', expecting end-of-input
If I remove self from def father(self), then I am getting this error:
person.rb:14:in `add_spouse': undefined method `spouse=' for #<Person:0x00005570928382d8> (NoMethodError)
My error was here: attr_accessor :spouse. I had to add this and to access it I had to do puts(p.father[0].name)
Is there a better way to implement the above class with similar other properties like father, children, brothers etc?