按字母顺序排序哈希值

时间:2017-08-16 08:44:02

标签: ruby

我在数组中有这个哈希

[{:name=>"Dr. Hannibal Lecter", :cohort=>:november, :hobby=>"driving", :birthplace=>"Ireland"}, {:name=>"Darth Vader", :cohort=>:november, :hobby=>"paragliding", :birthplace=>"England"}, {:name=>"Nurse Ratched", :cohort=>:november, :hobby=>"singing", :birthplace=>"Iceland"}, {:name=>"Michael Corleone", :cohort=>:march, :hobby=>"nature", :birthplace=>"Peru"}, {:name=>"Alex DeLarge", :cohort=>:may, :hobby=>"astronomy", :birthplace=>"Chile"}, {:name=>"The Wicked Witch of the West", :cohort=>:november, :hobby=>"adventure", :birthplace=>"Scotland"}, {:name=>"Terminator", :cohort=>:november, :hobby=>"crafting", :birthplace=>:Denmark}, {:name=>"Freddy Krueger", :cohort=>:may, :hobby=>"drawing", :birthplace=>:Eritrea}, {:name=>"The Joker", :cohort=>:august, :hobby=>"piano", :birthplace=>:Egypt}, {:name=>"Joffrey Baratheon", :cohort=>:march, :hobby=>"animals", :birthplace=>:Thailand}, {:name=>"Norman Bates", :cohort=>:august, :hobby=>"coffee", :birthplace=>:China}] 

使用此方法打印出来:

def print(students)
  students.each_with_index do |student, index|
  puts "#{index + 1}: #{student[:name]} (#{student[:cohort]} in cohort)   Hobby: #{student[:hobby]}, Birthplace: #{student[:birthplace]}".center(75)
  end
end

我希望按字母顺序对它们进行分组,我可以通过new_array_of_hashes = students.sort_by { |hsh| hsh[:cohort] }

进行分组

但是,如何将此方法集成到print(student)方法中?我仍然希望保留each_with_index方法,因为我想在每个学生面前保留一个打印号码,并按字母顺序对学生群组进行分组。

0 个答案:

没有答案
相关问题