class Person
attr_accessor :name, :age
def initialize name, age
self.name = name
self.age = age
end
end
arr = [
Person.new("tom", 12),
Person.new("John", 11),
Person.new("Bob", 11),
Person.new("Marry", 12)
]
hash = Hash.new
arr.each do |ele|
hash[ele.age] = Array.new if hash[ele.age].nil?
hash[ele.age] << ele
end
puts hash
比如上面的代码如果按照一个人的年龄来把 arr 这个数组转换为 Hash,还有什么更好的方法么,暂时只想到遍历,,