【发布时间】:2015-11-22 05:10:53
【问题描述】:
我是红宝石的菜鸟,所以对此持保留态度。
我有一个Person,已在下面发布。我应该使用姓氏搜索people 数组,并将结果返回到一个数组中,以便我可以使用诸如puts Person.search("Smith") 之类的put 语句打印它
这是我正在学习的课程:
class Person
attr_accessor :first_name,:last_name
@@people = []
def initialize(x,y)#should take 2 parameters for first_name and last_name
@first_name = x
@last_name = y
@@people << "#{@x} #{@y}"
end
#my problem is that the function is returning nill.
def self.search(last_name)
@results = []
@@people.each do |variable|
if variable.include? last_name
@results << variable
end
end
@results
end
def to_s
puts "#{@first_name} #{@last_name}"
#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")
我将results 声明为块外的空数组,因此我可以更改其值并在块内向其中添加项目,并在块范围外维护更改。但由于某种原因,该功能似乎不起作用。如何调试函数以便查明问题?
【问题讨论】: