如何从数组返回前三个值

时间:2021-10-19 16:41:07

I have a set of data:

我有一组数据:

grade_hash = {bill: [100, 95, 92], frank: [67, 73, 84], sue: [99, 88, 77], karen: [70,80,90], bob: [95, 93, 92]}

I also have a grade scale:

我也有一个年级:

def letter_grade(score)
  if score >= 90
   "A"
  elsif score >= 80
   "B"
  elsif score >= 70
   "C"
  elsif score >= 60
   "D"
  else
   "F"
  end
end

I want to extract those two that have the highest grades.

我想提取那些成绩最高的两个。

I have:

def top_students(grade_hash, number_of_students)
  grade_hash.transform_values {|nums| letter_grade(nums.reduce(:+)/nums.size)}
end

This would give the average of the grades for each student and apply a letter grade. How do I extract the top two?

这将给出每个学生的平均成绩并应用字母等级。如何提取前两个?

I tried applying a .sort_by but that didn't work.

我尝试应用.sort_by,但这不起作用。

1 个解决方案

#1


0  

To sort you will need to convert to an array. Hashes are not sortable.

要排序,您需要转换为数组。哈希不可排序。

grade_hash
  .transform_values {|nums| letter_grade(nums.reduce(:+)/nums.size)}
  .to_a
  .sort_by(&:last)

The above will sort the values.

以上将对值进行排序。

From there you can select the top n students and optionally convert back to a hash if you want to keep that format.

从那里你可以选择前n名学生,如果你想保留这种格式,可以选择转换回哈希。

grade_hash
  .transform_values {|nums| letter_grade(nums.reduce(:+)/nums.size)}
  .to_a               # this is superfluous; .sort_by on a hash will do this internally
  .sort_by(&:last)
  .take(number_of_students)
  .to_h

Addendum: CarySwoveland points out that arrays in ruby 2.4 support sum so the reduce isn't necessary

附录:CarySwoveland指出ruby 2.4中的数组支持总和,因此不需要减少

letter_grade(nums.sum.fdviv(nums.size))

#1


0  

To sort you will need to convert to an array. Hashes are not sortable.

要排序,您需要转换为数组。哈希不可排序。

grade_hash
  .transform_values {|nums| letter_grade(nums.reduce(:+)/nums.size)}
  .to_a
  .sort_by(&:last)

The above will sort the values.

以上将对值进行排序。

From there you can select the top n students and optionally convert back to a hash if you want to keep that format.

从那里你可以选择前n名学生,如果你想保留这种格式,可以选择转换回哈希。

grade_hash
  .transform_values {|nums| letter_grade(nums.reduce(:+)/nums.size)}
  .to_a               # this is superfluous; .sort_by on a hash will do this internally
  .sort_by(&:last)
  .take(number_of_students)
  .to_h

Addendum: CarySwoveland points out that arrays in ruby 2.4 support sum so the reduce isn't necessary

附录:CarySwoveland指出ruby 2.4中的数组支持总和,因此不需要减少

letter_grade(nums.sum.fdviv(nums.size))