user169320 user169320 - 1 month ago 7
Ruby Question

How can I create a to_s with an instance variable pointing to an array of objects from another class?

With the code below, I would like to create a

to_s
method that prints out information as such:

Southside has 3 team members.
Those members are: Dario, who is 22 years old. Ted, who is 21 years old. Bob, who is 44 years old.

Currently, I get this:

Southside has 3 team members.
Those members are:

[#<Person:0x000000025cd6e8 @name="Dario", @age=22>, #<Person:0x000000025cd670 @name="Ted", @age=21>, #<Person:0x000000025cd620 @name="Bob", @age=44>].
#<Team:0x000000025cd7d8>


The part I'm finding difficult is accessing the instance variables of the Person class objects that are in the Team members array.

Here are the two classes:

class Team
attr_accessor :name, :members

def initialize(name)
@name = name
@members = []
end

def <<(person)
members.push person
end

def to_s
puts "#{@name} has #{@members.size} team members."
puts "Those members are: #{@members}."
end
end

class Person
attr_accessor :name, :age

def initialize(name, age)
@name = name
@age = age
end
end

south_side_bowlers = Team.new("Southside")

south_side_bowlers << Person.new("Dario", 22)
south_side_bowlers << Person.new("Ted", 21)
south_side_bowlers << Person.new("Bob", 44)

puts south_side_bowlers

Answer

Define to_s ("#{@name}, who is #{@age} years old") for the Person class. Then you can do @members.map{ |m| m.to_s}.join('. ')

Comments