Im trying to return a list of values inside of of an array of hashes from lowest to highest. I am using the google_drive gem to pull numbers from a google spreadsheet, displaying football information:
Here is where I'm at:
require 'rubygems'
require 'google_drive'
session = GoogleDrive.login("EMAIL", "PASS")
v_qb_w1 = session.spreadsheet_by_key("xxxxxxxx").worksheets[0]
@quarterbacks = [
{ name: v_qb_w1[2, 1], projection: v_qb_w1[2, 2], salary: v_qb_w1[2, 3], dpp: v_qb_w1[2, 4], ppd: v_qb_w1[2, 5] },
{ name: v_qb_w1[3, 1], projection: v_qb_w1[3, 2], salary: v_qb_w1[3, 3], dpp: v_qb_w1[3, 4], ppd: v_qb_w1[3, 5] },
{ name: v_qb_w1[4, 1], projection: v_qb_w1[4, 2], salary: v_qb_w1[4, 3], dpp: v_qb_w1[4, 4], ppd: v_qb_w1[4, 5] }
]
puts "Value:"
@quarterbacks.sort_by do |key, value|
dpp = []
dpp << key[:dpp].to_f.to_s
puts dpp.flatten.sort.reverse
end
That last block was just one of my attempts to try and sort the :dpp key value from lowest to highest. Nothing fails, it just does not change anything. I've tried the grouby_by method and just have no luck arranging my key values
SOLUTION:
@quarterbacks.sort_by! { |qb| qb[:dpp] }
@quarterbacks.each { |qb| puts qb[:dpp] }
Try this
@quarterbacks.sort_by!{|qb| qb[:dpp]}
You are trying to sort an Array
. Right now you passing a Hash
(k) and nil
(v) because each quarterback is stored as a Hash
so there is no key => value
association in the Array
. Also puts will return nil
so you are telling it to sort nil
against nil
repetitively.
The code above will sort the Array
of Hash
es by the :dpp
attribute of each Hash
which seems like what you are asking for. The !
in this case means it will alter the receiver altering the @quarterbacks
instance variable to be sorted in place.
First of all, sort_by
returns the sorted list, it doesn't sort it in place. That means that just:
@quarterbacks.sort_by { ... }
doesn't do anything useful as you're throwing away the sorted results. You'd need to add an assignment or use sort_by!
:
@quarterbacks = @quarterbacks.sort_by { ... }
# or
@quarterbacks.sort_by! { ... }
Then you have understand how the sort_by
block works. sort_by
sorts using the block's return value, it is more or less like this:
array.map { |e| [ sort_by_block_value[e], e ] }
.sort { |a, b| a.first <=> b.first }
.map { |e| e.last }
so your block needs to return something sensible rather than the nil
that puts
returns:
@quarterbacks.sort_by! { |q| q[:dpp] }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.