繁体   English   中英

在哈希数组中获取 hash 的 position

[英]Get position of hash in array of hashes

我在一个数组中有一堆哈希。 每个 hash 都包含有关特定学生的信息。 我发现得分最高的学生( 'student_score'键)是这样的:

  top_student= array.max_by{ |k| k["student_score"]} 

然后我想写这样的消息:

  puts "The smartest student is (xxxxxx) with a test score of  #{top_student}"

其中xxxx应该是学生的编号(他的position在数组中)。

我需要知道它是哪个学生(此信息不是哈希中的键/值对)。 我想在该数组中确定 hash 的顺序,但我不确定。

如何获得学生的position?

一个哈希数组,每个 hash 代表一个学生:

students = [
  {'score' => 10, 'name' => 'Bob'},
  {'score' => 20, 'name' => 'Tom'},
  {'score' => 60, 'name' => 'Pete'},
  {'score' => 50, 'name' => 'Ane'}
]

best_student = students.max_by{|student| student['score']}

得到最高分的学生后,可以通过#index方法在数组中找到他的position:

index = students.index(best_student)
#=>2

所以你可以这样做:

puts "The best student is #{best_student['name']}, number #{index+1}, with a score of #{best_student['score']}."
#=>The best student is Pete, number 3, with a score of 60.

附带说明一下,应用程序数组中学生的 position 不应代表有关学生的信息,该信息应作为附加属性保存在 hash 中。 想象一下,如果您出于某种原因对数组进行排序,那么有价值的数据将会丢失。 如果您制作这样的数组,我认为您会更好:

students = [
  {'id' => 1, 'score' => 10, 'name' => 'Bob'},
...
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM