Tom K. C. Chiu
Tom K. C. Chiu

Reputation: 806

How to give a ruby class more than one of same attribute

https://github.com/babycaseny/Learning-Ruby/blob/master/ex42-pet.rb

Sorry for being noob: But seems I am not able to look for an answer.

I am working on a ruby exercise about class and attributes using people and pets as an example. I came to a question when answer the question about how to name the pet of Mary. "Well, Mary has a little lamb, right? How can I modify the class people so that it accept more than one pet for each person?" I can just define a new class called "Lamb" which is " < Animal". However, how can I modify "Person" so to accept more than one pet?

Upvotes: 0

Views: 59

Answers (1)

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

class Person

  def initialize(name)
    ## every person has a name
    @name = name

    ## Person may have many pets
    @pets = Array.new
  end

  attr_accessor :pets ## We can access attributes of their pets via the person
end

Upvotes: 1

Related Questions