0

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 : (

2
  • can you post the sample of hash after initializing? Commented Feb 23, 2014 at 9:01
  • Please improve your question by including whatever samples you're using as a corpus to test against. Also, include a properly-formatted sample of your expected output so folks understand the results you're trying to achieve. Commented Feb 23, 2014 at 16:47

3 Answers 3

1
result_hash = {} hash.each do |key, array| result_hash[key] = array.find_all({|item| item.promo_code = 24}).length end 
Sign up to request clarification or add additional context in comments.

3 Comments

this seems like its supposed to work but i still get result_hash[key]= nil :(
It may relative to the data structure inside the hash instance. According to your description the data inside the hash may have the structure like this. {:1 => [{:promo_code => 1}, {:promo_code => 2}, ...], :2 => [{:promo_code => 1}, {:promo_code => 24}, ...], ...}. Check it out of your hash instance and see whether this is right.
i posted more info maybe you can help me ? : )
0
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.

Comments

0

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"}) } 

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.