简体   繁体   中英

extracting data from a hash of arrays in ruby

I'm new to ruby and working on a large data project and I'v got a nooby question.

I'v got a hash containing data of sales which is sorted by stores id:

hash = Hash.new(Array.new))
Sale.all.each {|sale| hash[sale.store_id].push( JSON.parse(sale.data)['items']) }

Now, I want to run over each store_id and get every item.promo_code = 24 and say how many item are there for each store.id .

Here is the data structure of the array inside of each key:

hash => 1 : Array [[{DATA,DATA,DATA}{DATA,DATA,DATA}]]

How would this be done in ruby?

Thank you very much in advance

EDIT:

I decided to attack this problem from a different angle

Sale.all.each {|sale| arr[sale.store_id] +=1 if (JSON.parse(sale.data)['items'].each{|item| item['buy_promotion_code']} == 24)  }

doesn't get me anything i get arr[#] = 0 all the time help : (

result_hash = {}

hash.each do |key, array|
  result_hash[key] = array.find_all({|item| item.promo_code = 24}).length
end
result_hash = {}

hash.each do |key, array|
  result_hash[key] += 1 if array[0] == 24
  puts array
end

where array[0] should give the value of promo_code of each item in the array.

My friend helped me with this.

he showed me the count function which simplified all this mess

this is the line that worked for me :

Sale.all.each {|sale| arr[sale.store_id] +=  (JSON.parse(sale.data)['items'].count {|item|  item['buy_promotion_code'] == "-1"}) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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