【问题标题】:Searching an element of an array against all elements of another array根据另一个数组的所有元素搜索一个数组的元素
【发布时间】:2015-02-21 19:39:30
【问题描述】:

我创建了一个脚本,允许我将 CSV 作为多维数组导入,对数组的每一行运行搜索,如果搜索字符串与一行中的任何元素匹配,则将整行返回到新数组,通过写作:

require 'csv'
array = CSV.read('CSVlist.csv') #=> [["Name1", "8675309"],["Name2", "5557891"], ["Name3", "5557890"]]
shifted_array = Array.new
results_array = Array.new

while array.empty? == false
    shifted_array = array.shift 
    shifted_array.each do |f|
        if f =~ /8675309/  
           shifted_array = shifted_array.join(",") #=> ["Name1,8675309"]
           results_array.push(shifted_array)
        end
    end
end
puts results_array #=> ["Name1,8675309"]

以上工作正常。但是,我想搜索整个数组并返回另一个数组(这是一个导入的文本文件)中的任何元素,而不是仅仅搜索一个字符串(上面的/8675309/)。我已经创建了比较数组,但是如何根据另一个数组(numbers_array,下面)而不是字符串来搜索主数组(array)?

require 'csv'
array = CSV.read('CSVlist.csv') #=> [["Name1", "8675309"],["Name2", "5557891"], ["Name3", "5557890"]]
shifted_array = Array.new
results_array = Array.new
numbers_array = File.readlines("list1.txt").map &:split #=> ["5551234", "5557890", "8675309"]

while array.empty? == false
    shifted_array = array.shift
    shifted_array.each do |f|
        if f =~ ???? # want the search to compare f to any element in numbers_array  
            shifted_array = shifted_array.join(",")
           results_array.push(shifted_array)
        end
    end
end
puts results_array  #=> desired output is ["Name1,8675409", "Name3,5557890"]

【问题讨论】:

  • 不要发布代码。写下你想要做的事情(最好是示例输入、输出)。
  • @sawa 代码也不错!两者都比其中一个更好。

标签: ruby arrays search


【解决方案1】:

您可以使用.select.any?.include?.map,它们加在一起看起来像:

results_array = array.select{ |row|
  row.any?{ |e| numbers_array.include? e }
}.map{ |row|
  row.join(',')
}

此代码首先选择array的行包括任何numbers_array中的元素,然后join映射每一张。

使用该语句,您的整个代码块可以缩短为:

require 'csv'

array = CSV.read('CSVlist.csv')
numbers_array = File.readlines('list1.txt').map(&:split)

results_array = array.select{ |row|
  row.any?{ |e| numbers_array.include? e }
}.map{ |row|
  row.join(',')
}

puts results_array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多