简体   繁体   English

检查哈希映射数组中是否存在某些值

[英]Check if certain value exists in array of hash map

I have an array of hash map. 我有一个哈希映射数组。 It looks like this: 看起来像这样:

params = []
CSV.foreach(......) do
  one_line_item = {}
  one_line_item[:sku] = "Hello"
  one_line_item[:value] = "20000"
  params << one_line_item
end

I want to check if :sku is in this array of hash or not. 我想检查:sku是否在此哈希数组中。 I am doing it like this: 我这样做是这样的:

# Reading new line of csv in a hash and saving it in a temporary variable (Say Y)
params.each do |p|
  if p[:sku] == Y[:sku]
    next
  end
end

I am iterating through the complete list for every value of sku, and thus time complexity is going for a toss [O(n^2)], need less to say it is useless. 我正在遍历sku的每个值的完整列表,因此时间复杂度在折腾[O(n ^ 2)],不用说这是没有用的。

Is there a way I can use include? 有没有办法使用include? ?

If I can get an array of values corresponding to the key :sku from the whole array in one shot, it would solve my problem. 如果我可以一次从整个数组中获取与键:sku对应的值数组,那将解决我的问题。 (I know I can maintain another array for these values but I want to avoid that) (我知道我可以为这些值维护另一个数组,但我想避免这种情况)

One example of params 参数的一个例子

params = [{:sku=>"hello", :value=>"5000"}, {:sku=>"world", :value=>"6000"}, {:sku=>"Hi", :value=>"7000"}]

The any? any? and include? include? methods sound like what you need. 方法听起来像您所需要的。

Example: 例:

params.any? { |param| param.include?(:sku) }

This is an efficient way to do it, as it "short circuits", stopping as soon as a match is found. 这是一种有效的方法,因为它“短路”,一旦找到匹配项就会立即停止。

So what you want is to collect a list of all SKUs. 因此,您想要的是收集所有SKU的列表。 Are you looking to key sku => value? 您是否要输入sku =>值?

Hash[*params.map { |p| [p[:sku], p[:value]] }.flatten]

That will give you a map of each sku to the value, which you can then do quick key lookups with sku_hash.key?(tester) 这将为您提供每个sku到值的映射,然后您可以使用sku_hash.key进行快速键查找?(测试器)

You may use rails_param gem for doing the same. 您可以使用rails_param gem进行相同的操作。 I find it a very useful utility for validation request params in controller: 我发现它对于控制器中的验证请求参数非常有用:

https://github.com/nicolasblanco/rails_param https://github.com/nicolasblanco/rails_param

# primitive datatype syntax
param! :integer_array, Array do |array,index|
  array.param! index, Integer, required: true
end

# complex array
param! :books_array, Array, required: true  do |b|
  b.param! :title, String, blank: false
  b.param! :author, Hash, required: true do |a|
    a.param! :first_name, String
    a.param! :last_name, String, required: true
  end
  b.param! :subjects, Array do |s,i|
    s.param! i, String, blank: false
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM