【问题标题】:search array in ruby and return results as collection of objects?在ruby中搜索数组并将结果作为对象集合返回?
【发布时间】: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 声明为块外的空数组,因此我可以更改其值并在块内向其中添加项目,并在块范围外维护更改。但由于某种原因,该功能似乎不起作用。如何调试函数以便查明问题?

【问题讨论】:

    标签: arrays ruby search


    【解决方案1】:

    您的代码中有错误。你需要使用

    @@people << "#{x} #{y}"
    

    xy 是局部变量,你不应该在它前面加上 @,因为 @x@y 只适用于实例变量

    【讨论】:

    • 我在初始化函数中已经这样做了吗?我错过了什么?
    • 是的,您不能使用@ 来引用局部变量。
    • 哦,我刚刚注意到了。感谢您指出。问题解决了 !谢谢。
    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2019-06-26
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多