给出以下代码:
class Person
attr_accessor :first_name, :last_name
@@people = []
def initialize(first_name,last_name)
@first_name = first_name
@last_name = last_name
@@people.push(self)
end
def self.search(last_name)
@last_name = last_name #accept a `last_name` parameter
@@people.select { |person| person.last_name }
#return a collection of matching instances
end
#have a `to_s` method to return a formatted string of the person's name
def to_s
#return a formatted string as `first_name(space)last_name`
end
end
p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")
puts Person.search("Smith")
# Should print out
# => John Smith
# => Jane Smith
我需要怎么做才能返回该Should print out
位的输出?我可以得到它返回对象ID:
#<Person:0x007fa40c04cd08>
#<Person:0x007fa40c04c920>
#<Person:0x007fa40c04c5d8>
#<Person:0x007fa40c04c5b0>
我看到的一个问题甚至都不知道每个问题是什么:应该只返回两个值。显然,搜索部分也是错误的。
我该怎么办?
class Person
attr_accessor :first_name, :last_name
@@people = []
def initialize(first_name,last_name)
@first_name = first_name
@last_name = last_name
@@people.push(self)
end
def self.search(last_name)
@@people.select { |person| person.last_name == last_name }
#return a collection of matching instances
end
#have a `to_s` method to return a formatted string of the persons name
def to_s
"#{self.first_name} #{self.last_name}"
end
end
p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")
puts Person.search("Smith").collect(&:to_s)
我已经更改了self.search方法,以选择具有相同姓氏的对象,并且显然选择了to_s方法和输出的内容。进行阅读测试,如果您还有其他问题,请告诉我
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句