arrays - Ruby 数组搜索方法未按预期工作

标签 arrays ruby search methods

我在脚本中编写的搜索方法无法正常工作。以下是脚本中的相关代码:

$records = []

def xml_extractor(document)
    document.xpath("//record").each do |record|
        $records << {"id" => record.xpath('id').text, 
            "first_name" => record.xpath('first_name').text, 
            "last_name" => record.xpath('last_name').text, 
            "email" => record.xpath('email').text, 
            "gender" => record.xpath('gender').text, 
            "ip_address" => record.xpath('ip_address').text,
            "send_date" => record.xpath('send_date').text,
            "email_body" => record.xpath('email_body').text,
            "email_title" => record.xpath('email_title').text}
            puts record
        end
    puts "\nAll records loaded!"
end


def search_by_ip(ip)
    record_to_return = $records.select {|k| k["ip_address"] == ip.to_s}
    puts JSON.pretty_generate(record_to_return) 
end

基本上我的 xml_extractor 方法工作正常,它使用 nokogiri 将所有内容存储到数组中。正在实现的 xml 文件有上千条记录,每条记录都有自己的名字、姓氏等。但问题是,当我尝试在数组上实现 search_by_ip 方法时,会返回一个“空”值,而实际上该方法应该是什么这样做是返回属于该特定 ip 地址的整个记录​​。此外,我意识到每次执行 xml_extractor 方法时,即当将 xml 文档解析到数组中时,内容并没有真正保存在其中,而是仅在循环进行时显示。这可能就是为什么我的搜索方法得到“空”的原因。让我知道你们的想法。

最佳答案

我写了一个例子,说明如何使用OO来获得你想要的东西。 我没有你的文档,所以我将你的文档简化为二维数组 在读取方法中切换注释以使用您的 xml 每个方法都可以链接起来,并且只做需要的事情 它们都可以单独测试(这里通过 p'ting 它们)

class Xml_extractor

  attr_reader :document, :records

  def initialize document
    @document = document
    @records  = []
  end

  def read
    # @document.xpath("//record").each do |record|
    @document.each do |record|
      @records << {id: record[0], ip_address: record[1]}
    end
    self # return self so that you can chain another method
  end

  def search_by_ip(ip)
    #return first of an array if found, nil otherwise
    # attention to use a hash key here to search, not a string
    @records.select {|k| k[:ip_address] == ip.to_s}.first
  end

end

document = [[0, "192.168.0.1"], [1, "192.168.0.2"]]
p Xml_extractor.new(document).read.records
# [{:id=>0, :ip_address=>"192.168.0.1"}, {:id=>1, :ip_address=>"192.168.0.2"}]
p Xml_extractor.new(document).read.search_by_ip("192.168.0.2")
# [{:id=>1, :ip_address=>"192.168.0.2"}]
p Xml_extractor.new(document).read.search_by_ip("192.168.0.2").to_json
# "[{\"id\":1,\"ip_address\":\"192.168.0.2\"}]"

关于arrays - Ruby 数组搜索方法未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347476/

相关文章:

C# 以数组形式返回 json 结果

javascript - 将 javascript 对象数组转换为 JSON

arrays - 在 Swift 中展平多个数组的所有值

ruby-on-rails - 我缺少 Solr-Sunspot 设置的哪一部分?

search - 使用River插件时如何创建初始Elasticsearch设置

c - OpenGL 绘制缓冲区问题

ruby - Rufus-Scheduler、DaemonKit 和陷阱

ruby - 测试一个方法是否需要一个 block

ruby-on-rails - rest_in_place 在 .each for 循环中选择

使用属性过滤 Django-sphinx 结果?