如何在ruby中打印类变量数组的元素



我刚开始学习ruby,无法找到为@@people数组的每个元素打印first_name和last_name的解决方案。。。

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

为什么要让类Person容纳一组人?

如果您只是将person对象封装在一个数组中,然后对它们进行迭代并调用它们的first_namelast_name访问器,则会更容易:

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"

最新更新