Reputation: 497
Recently started learning ruby and I've created a class for family members that contains name, age, sex, marital status, and traits. I am trying to write a method that will determine if a family member is a parent and if whether or not its the mother or the father.
so the code for the method is as follows:
def is_father?(age, sex)
if age > 30
puts "is parent"
if sex == "Male"
then puts "is father"
else puts "not father"
end
end
end
And a family member might look like this:
fm1=Family.new("John", "Male", 54, "Married", "Annoying")
after being initialized like this:
class Family
def initialize(name, sex, age, status, trait)
@fam_name=name
@fam_sex=sex
@fam_age=age
@fam_stat=status
@fam_trait=trait
end
end
If a person contains the previously mentioned characteristics, how do I just pass age + sex into this method? Thanks in advance for your help
Upvotes: 0
Views: 174
Reputation: 21791
Using Struct can save a banch of code
class Family < Struct.new(:name, :sex, :age, :status, :trait)
# define methods in usual manner
end
f = Family.new("John", 'male') #<struct Family name="John", sex="male", age=nil, status=nil, trait=nil>
Upvotes: 0
Reputation:
Once you initialized age/sex/etc you can use them in any method by @age
/@sex
/@etc
def is_father?(age = nil, sex = nil)
if (age || @age) > 30
puts "is parent"
end
if (sex || @sex) == "Male"
puts "is father"
else
puts "not father"
end
end
In example above if you pass values to the method, they will be used instead ones set at initialization
Upvotes: 0
Reputation: 27845
You must store your data during initialization in attributes. later you can use them without using parameters of the method.
Example:
class Family
def initialize(name, sex, age, status, trait)
@fam_name=name
@fam_sex=sex
@fam_age=age
@fam_stat=status
@fam_trait=trait
end
def is_parent?; @fam_age > 30;end
def is_father?
is_parent? and @fam_sex == "Male"
end
def to_s
result = @fam_name.dup
if @fam_age > 30
result << " is parent and is "
if @fam_sex == "Male"
result << "father"
else
result << "not father"
end
end
result
end
end
fm1=Family.new("John", "Male", 54, "Married", "Annoying")
puts fm1.ilding is_parent?
puts fm1.is_father?
puts fm1
Remarks:
is_father?
- methods ending on ?
normally returns a boolean value.to_s
. to_s
is called if you print your object with puts
.puts
inside your methods. Most of the times, it is better to return an answer string and make the puts
when you call the method.Perhaps I misunderstand your request.
If is_father?
is no method of Family and you need access to the attributes, then you must define a getter method:
class Family
def initialize(name, sex, age, status, trait)
@fam_name=name
@fam_sex=sex
@fam_age=age
@fam_stat=status
@fam_trait=trait
end
attr_reader :fam_sex
attr_reader :fam_age
end
fm1=Family.new("John", "Male", 54, "Married", "Annoying")
puts fm1.fam_sex
puts fm1.fam_age
is_father?(fm1.fam_age, fm1.fam_sex)
Upvotes: 1