给出以下代码:
STARTUPINFO
在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
位下返回输出需要做什么?我可以让它返回对象id:
Should print out
我看到的一个问题,即使不知道每个内容是什么:应该只返回两个值。很明显,搜索部分也是错误的。
我应该怎么做呢?
答案 0 :(得分:1)
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方法+得到的东西。如果您有任何其他问题,请阅读测试并告诉我
答案 1 :(得分:0)
在@@ Person上添加条件和maping数组。 代码在这里描述:
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 = @@people.select { |person| person.last_name == @last_name }.map{|p| p.first_name.to_s + ' ' + p.last_name.to_s}
#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")