ruby on rails - How do I extract array values from hashes? -


i'm struggling data structures in ruby.

i have:

answers = [     {"val"=>["6"], "comment"=>["super"], "qid"=>["2"]},     {"val"=>["3"], "comment"=>[""], "qid"=>["1"]},     {"val"=>["7"], "comment"=>[""], "qid"=>["4"]},     {"val"=>["5", "6"], "comment"=>["supera", "hmm"], "qid"=>["1", "2"]},     {"val"=>["5", "9"], "comment"=>["super", "asdf"], "qid"=>["1", "5"]} ] 

i need following arrays qid's, should unique, on hashes:

["2","1","4","5"] # note, value 2 exists 2 times , value 1, 3 times  

the corresponding values should summarized , divided through number of counts:

["12","13","7","9"] be: ["6","4.3","7","9"] # 12/2 , 13/3 

the comments should summarized well:

[["super","hmm"],["","supera","super"],[""],["asdf"]] 

i'm wondering if it's cool put in hash?

so far have:

a = hash.new(0)   answers.each.map { |r| r }.each |variable|     variable["qid"].each_with_index |var, index|         #a[var] << { :count => a[var][:count] += 1 }         #a[var]["val"] += variable["val"][index]         #a[var]["comment"] = a[var]["comment"].to_s + "," + variable["comment"][index].to_s     end      end 

i'm trying generate data highcharts demo - basic bar. gem lazyhighcharts

any ideas? suggestions?

edit:

maybe have explain again structure: there questions id's (qid), each of them has value , comment, trying calculate average of "val" hashes

ok, think understand you're shooting for...

# lets create hash store data # such my_data[qid][0] => value sum #           my_data[qid][1] => number of times qid appeared #           my_data[qid][2] => comments array  my_data = {}  # go through answers , fill my_data out  answers.each |h|     in 0...h["qid"].length         qid = h["qid"][i]          # awesome ruby syntax set my_data[qid]          # if hasn't been set using "or-equals" operator         my_data[qid] ||= [0, 0, []]           my_data[qid][0] += h["val"][i].to_i # add value         my_data[qid][1] += 1                # increment count         my_data[qid][2] << h["comment"][i]  # add comment     end  end  # how data out qid of "2"  my_data["2"][0].to_f / my_data["2"][1] # => 6 my_data["2"][2]                        # => ["super", "hmm"]  # , process qid, or qids iterating on # my_data. build arrays in op  qids = [] average_values = [] comments = []  my_data.each |k, v|     qids << k     average_values << v[0].to_f / v[1]     comments << v[2] end  # qids           => ["2", "1", "4", "5"] # average_values => [6, 4.3, 7, 9] # comments       => [["super", hmm"] ["", "supera", "super"], [""], ["asdf"]] 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -