user169320 user169320 - 1 year ago 58
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

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>].

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 = []

def <<(person)
members.push person

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

class Person
attr_accessor :name, :age

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

south_side_bowlers ="Southside")

south_side_bowlers <<"Dario", 22)
south_side_bowlers <<"Ted", 21)
south_side_bowlers <<"Bob", 44)

puts south_side_bowlers

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download