Ruby 类数组按照某一个属性值转 Hash

msms · 2014年07月24日 · 最后由 Msms 回复于 2014年07月24日 · 2097 次阅读

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,还有什么更好的方法么,暂时只想到遍历,,

puts arr.group_by &:age

#1 楼 @saiga 好吧,果然很强大,我在 Array 和 Hash 的手册里找了半天没找到合适的函数, 还是经验值不够呀,,

需要 登录 后方可回复, 如果你还没有账号请 注册新账号