Reputation: 475
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 : (
Upvotes: 0
Views: 258
Reputation: 475
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"}) }
Upvotes: 0
Reputation: 1692
result_hash = {}
hash.each do |key, array|
result_hash[key] = array.find_all({|item| item.promo_code = 24}).length
end
Upvotes: 1
Reputation: 22926
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.
Upvotes: 0