Reputation: 5
I'm looking to print out the name and status variables for each instance of the FamilyMember class. I've created the instances and added them to an array. When I attempt to loop through the array using the .each method the name and status variables are not recoignised. Any help would be greatly appreciated.
class FamilyMember
attr_reader :name, :age, :sex, :status, :country
def initialize (name, age, sex, status, country)
@name = name
@age = age
@sex = sex
@status = status
@country = country
end
def parent?
end
def child?
end
end
fm1 = FamilyMember.new('Scott', 18 , 'Male', 'Employed', 'America'),
fm2 = FamilyMember.new('Stephen', 30, 'Male', 'Employed', 'Ireland'),
fm3 = FamilyMember.new('Gillian', 50, 'Female', 'Employed', 'Ireland'),
fm4 = FamilyMember.new('Rolf', 56, 'Male', 'Employed', 'Ireland'),
fm5 = FamilyMember.new('Shane', 14, 'Male', 'Unemployed', 'Ireland')
array_1 = Array.new
array_1 << fm1
array_1 << fm2
array_1 << fm3
array_1 << fm4
array_1 << fm5
array_1.each do |p| #Trying to print out the name and status values for each instance.
puts "#{p.name} is #{p.status}"
end
Upvotes: 0
Views: 83
Reputation: 37409
Your problem is that you ended each instance creation line in your code with ,
. That's why fm1
is actually created as an array instead of a FamilyMember
fm1.class
# => Array
simply remove the ,
at the end of lines:
fm1 = FamilyMember.new('Scott', 18 , 'Male', 'Employed', 'America')
fm2 = FamilyMember.new('Stephen', 30, 'Male', 'Employed', 'Ireland')
fm3 = FamilyMember.new('Gillian', 50, 'Female', 'Employed', 'Ireland')
fm4 = FamilyMember.new('Rolf', 56, 'Male', 'Employed', 'Ireland')
fm5 = FamilyMember.new('Shane', 14, 'Male', 'Unemployed', 'Ireland')
and try again:
array_1 = Array.new
array_1 << fm1
array_1 << fm2
array_1 << fm3
array_1 << fm4
array_1 << fm5
array_1.each do |p|
puts "#{p.name} is #{p.status}"
end
Output:
Scott is Employed
Stephen is Employed
Gillian is Employed
Rolf is Employed
Shane is Unemployed
Upvotes: 3