title: Ruby - Array of Hashes, Trying to Select Multiple Keys and Group By Key Value
body: <p>I have a set of data that is an array of hashes, with each hash representing one record of data:</p>
  
  <pre><code>data = [
    {
      :id =&gt; "12345",
      :bucket_1_rank =&gt; "2",
      :bucket_1_count =&gt; "12",
      :bucket_2_rank =&gt; "7",
      :bucket_2_count =&gt; "25"
    },
    {
      :id =&gt; "45678",
      :bucket_1_rank =&gt; "2",
      :bucket_1_count =&gt; "15",
      :bucket_2_rank =&gt; "9",
      :bucket_2_count =&gt; "68"
    },
    {
      :id =&gt; "78901",
      :bucket_1_rank =&gt; "5",
      :bucket_1_count =&gt; "36"
    }
  ]
  </code></pre>
  
  <p>The ranks values are always between 1 and 10.</p>
  
  <p>What I am trying to do is select each of the possible values for the rank fields (the <code>:bucket_1_rank</code> and <code>:bucket_2_rank</code> fields) as keys in my final resultset, and the values for each key will be an array of all the values in its associated <code>:bucket_count</code> field.  So, for the data above, the final resulting structure I have in mind is something like:</p>
  
  <p>bucket 1:</p>
  
  <pre><code> {"2" =&gt; ["12", "15"], "5" =&gt; ["36"]}
  </code></pre>
  
  <p>bucket 2:</p>
  
  <pre><code>{"7" =&gt; ["25"], "9" =&gt; ["68"]}
  </code></pre>
  
  <p>I can do this working under the assumption that the field names stay the same, or through hard coding the field/key names, or just using <code>group_by</code> for the fields I need, but my problem is that I work with a different data set each month where the rank fields are named slightly differently depending on the project specs, and I want to identify the names for the count and rank fields dynamically as opposed to hard coding the field names.</p>
  
  <p>I wrote two quick helpers <code>get_ranks</code> and <code>get_buckets</code> that use regex to return an array of fieldnames that are either ranks or count fields, since these fields will always have the literal string "_rank" or "_count" in their names:</p>
  
  <pre><code>ranks = get_ranks
  counts = get_counts
  
  results = Hash.new{|h,k| h[k] = []}
  
  data.each do |i|
    ranks.each do |r|
      unless i[r].nil?
        counts.each do |c|
            results[i[r]] &lt;&lt; i[c]
        end
      end
    end
  end
  
  p results
  </code></pre>
  
  <p>This seems to be close, but feels awkward, and it seems to me there has to be a better way to iterate through this data set. Since I haven't worked on this project using Ruby I'd use this as an opportunity to improve my understanding iterating through arrays of hashes, populating a hash with arrays as values, etc. Any resources/suggestions would be much appreciated.</p>