0

This query response contains a delta pair that is computed so that I don't have to unnecessarily create another column in the database.

records = [
  {"credential_id"=>1, "followers_count"=>10000, "created_at"=>"2017-02-26 18:50:20.654996", "delta"=>nil}, 
  {"credential_id"=>1, "followers_count"=>12000, "created_at"=>"2017-02-27 18:50:20.654996", "delta"=>2000}, 
  {"credential_id"=>1, "followers_count"=>15000, "created_at"=>"2017-02-28 18:50:20.654996", "delta"=>3000}
]

Desired result:

deltas = [
  [2017-02-26 18:50:20.654996, nil],
  [2017-02-27 18:50:20.654996, 2000],
  [2017-02-28 18:50:20.654996, 3000]
]

Attempts -- However, I think the fact that :delta is not part of the model/table is preventing me from using the following solutions: .pluck(:created_at, :delta), .values_at("created_at", "delta"), and

attributes = [:created_at, :delta]    

records.map do |record|
  attributes.map { |attr| record[attr] }
end

I've run out of solutions to try. Can you help me find the desired result?

3 Answers 3

1

It's actually simple:

records.map { |h| [h['created_at'], h['delta']] }
 => [["2017-02-26 18:50:20.654996", nil], 
     ["2017-02-27 18:50:20.654996", 2000], 
     ["2017-02-28 18:50:20.654996", 3000]]

In Ruby, you can access hash value by passing key name in brackets, like in this instance.

Or you can use Hash#values_at:

records.map { |h| h.values_at('created_at', 'delta') }

and get the same result.

Sign up to request clarification or add additional context in comments.

Comments

0

Replace the attributes symbols with strings :

attributes = ['created_at', 'delta']    

Comments

0

You just need to iterate over the records hash with .map, and assign the 'created_at' and 'delta' fields to a new array. Array#map allows you to mutate the starting objects as you go.

records.map {|r| [r['created_at'], r['delta']]}

From the docs:

Array#map

Creates a new array containing the values returned by the block.

Ruby Docs for map

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.