Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I extract array values from hashes?
    primarykey
    data
    text
    <p>I'm struggling with a data structures in Ruby.</p> <p>I have:</p> <pre><code>answers = [ {"val"=&gt;["6"], "comment"=&gt;["super"], "qid"=&gt;["2"]}, {"val"=&gt;["3"], "comment"=&gt;[""], "qid"=&gt;["1"]}, {"val"=&gt;["7"], "comment"=&gt;[""], "qid"=&gt;["4"]}, {"val"=&gt;["5", "6"], "comment"=&gt;["supera", "hmm"], "qid"=&gt;["1", "2"]}, {"val"=&gt;["5", "9"], "comment"=&gt;["super", "asdf"], "qid"=&gt;["1", "5"]} ] </code></pre> <p>I need the following arrays for the qid's, which should be unique, all over the hashes:</p> <pre><code>["2","1","4","5"] # note, value 2 exists two times and value 1, 3 times </code></pre> <p>The corresponding values should be summarized and divided through number of counts:</p> <pre><code>["12","13","7","9"] will be: ["6","4.3","7","9"] # 12/2 and 13/3 </code></pre> <p>The comments should be summarized as well:</p> <pre><code>[["super","hmm"],["","supera","super"],[""],["asdf"]] </code></pre> <p>I'm wondering if it's cool to put it together in an hash?</p> <p>So far I have:</p> <pre><code>a = Hash.new(0) answers.each.map { |r| r }.each do |variable| variable["qid"].each_with_index do |var, index| #a[var] &lt;&lt; { :count =&gt; 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 </code></pre> <p>I'm trying to generate data for <a href="http://www.highcharts.com/demo/bar-basic" rel="nofollow">Highcharts Demo - Basic bar</a>. The gem is <a href="https://github.com/michelson/lazy_high_charts" rel="nofollow">LazyHighCharts</a></p> <p>Any Ideas? Suggestions?</p> <p><strong>Edit:</strong></p> <p>Maybe I have to explain again the structure: there are questions id's (qid), each of them has a value and a comment, I am trying to calculate the average of the "val" hashes</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload