0

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 
1
  • The assignment as stated is impossible. Returning a string from print_name cannot possibly print out anything to the console. The assignment cannot be completed as stated. Commented Apr 1, 2020 at 18:30

1 Answer 1

2

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" 
Sign up to request clarification or add additional context in comments.

3 Comments

I' m new to ruby and it's my homework to do in the prescribed way...I even searched google but I' m unable to get through...
Give me a hand then. Should you instantiate them separately? Or you can directly pass the number of persons to be isntantiated and then push them to @@people?
The problem is @@people is directly attached to a single instance of person. Anyway, you can try moving the class variable outside the class, not impossible, but also not recommended at all. @@people = [] class Person attr_accessor :first_name, :last_name def initialize(x, y) @first_name = x @last_name = y @@people.push(self) end def print_name p "#{first_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") @@people.each(&:print_name).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.