陣列返回對象考慮下面的代碼:從紅寶石
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>
的一個問題,我與看到,甚至不知道什麼是每個人:應該只有返回兩個值。顯然,搜索部分也是錯誤的。
我該怎麼做?
你應該實現'Person#to_s'來完成評論所說的內容 - *「#返回格式化的字符串作爲first_name(空格)last_name」* - 然後迭代在'Person#search'返回並在每個對象上調用'Person#to_s'。 –
此外您的搜索方法不正確。 – andrewkday