1

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. 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.

Is there a way I can use 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. (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"}] 
1
  • can you please post an example of populated params? Commented Feb 16, 2015 at 7:19

3 Answers 3

3

The any? and 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Going with some thing similar "params.any? { |p| p.values.member?("hello") }"
0

So what you want is to collect a list of all SKUs. Are you looking to key sku => value?

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)

Comments

0

You may use rails_param gem for doing the same. I find it a very useful utility for validation request params in controller:

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.