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, :spouse
def initialize(name, gender, mother = nil)
@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?
In python if I want a class method as a property then @property
is used. In Ruby is there anything like that or is the above method for father
property correct?
Also I have seen examples with self.some_variable
and @some_variable
in Ruby. Here name
and gender
variables are defined at the object creation and never changed but other variables like mother
, children
can be nil
initially and can be added by some other external method. For eg: By a method add_member
in class Family
. So for that is the above definition correct?
SyntaxError
, it isn't even legal Ruby. You might get better help on Stack Overflow, but please make sure to produce a minimal reproducible example. In particular, theSyntaxError
can be trivially reproduced in one line, it doesn't require 22 lines of code to show. \$\endgroup\$self
indef father
initially. Then I changed it in my code but while typing the question I mistyped it. I have changed it now. \$\endgroup\$