ravi
ravi

Reputation: 55

how to print elements of a class variable array in ruby

I have just started learning ruby and I am unable to find out a solution on printing first_name and last_name for each element of @@people array...

class Person
    #have a first_name and last_name attribute with public accessors
    attr_accessor :first_name, :last_name

    #have a class attribute called `people` that holds an array of objects
    @@people = []

    #have an `initialize` method to initialize each instance
    def initialize(x,y)#should take 2 parameters for first_name and last_name
    #assign those parameters to instance variables
      @first_name = x
      @last_name = y
      #add the created instance (self) to people class variable
      @@people.push(self)
    end

    def print_name
      #return a formatted string as `first_name(space)last_name`
      # through this method i want to print first_name and last_name
    end  
end

p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")



# Should print out
# => John Smith
# => John Doe
# => Jane Smith
# => Cool Dude

Upvotes: 0

Views: 948

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

Why would you make the class Person to hold an array of persons?

It's easier if you just wrap your person objects in an array and then iterate over them and invoke their first_name and last_name accessors:

class Person
  attr_accessor :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end
end

p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")

[p1, p2, p3, p4].each { |person| p "#{person.first_name} #{person.last_name}" }
# "John Smith"
# "John Doe"
# "Jane Smith"
# "Cool Dude"

Upvotes: 2

Related Questions