Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like you can do this by applying two different <code>group_by</code> operations:</p> <pre><code>data = [ {"userid"=&gt;"1", "num"=&gt;"1", "amount"=&gt;"15.00"}, {"userid"=&gt;"2", "num"=&gt;"1", "amount"=&gt;"19.00"}, {"userid"=&gt;"3", "num"=&gt;"1", "amount"=&gt;"25.00"}, {"userid"=&gt;"4", "num"=&gt;"1", "amount"=&gt;"30.00"}, {"userid"=&gt;"5", "num"=&gt;"2", "amount"=&gt;"15.00"} ] # Establish the arbitrary groupings as a set of functions which # can be evaluated. If these overlap in ranges, the first match # will be used. groupings = [ lambda { |v| v &gt;= 0 &amp;&amp; v &lt;= 20 }, lambda { |v| v &gt; 20 &amp;&amp; v &lt;= 50 }, lambda { |v| v &gt; 50 &amp;&amp; v &lt;= 80 }, lambda { |v| v &gt; 80 } ] data.group_by do |element| # Group by the 'num' key first element['num'] end.flat_map do |num, elements| # Then group these sets by which of the range buckets # they should be sorted into. elements.group_by do |element| # Create an array that looks like [ false, true, false, ... ] # based on the test results, then find the index of the # first true entry. groupings.map do |fn| fn.call(element['amount'].to_f) end.index(true) end.values end # =&gt; [[{"userid"=&gt;"1", "num"=&gt;"1", "amount"=&gt;"15.00"}, {"userid"=&gt;"2", "num"=&gt;"1", "amount"=&gt;"19.00"}], [{"userid"=&gt;"3", "num"=&gt;"1", "amount"=&gt;"25.00"}, {"userid"=&gt;"4", "num"=&gt;"1", "amount"=&gt;"30.00"}], [{"userid"=&gt;"5", "num"=&gt;"2", "amount"=&gt;"15.00"}]] </code></pre> <p>Calling <code>.values</code> on the result of a <code>group_by</code> will give you just the grouped sets, not the keys that indicate which group they are.</p>
 

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