返回顶部

收藏

Sort object array by object attribute

更多
class Person

  attr_reader :name, :age, :height

  def initialize(name, age, height)
    @name, @age, @height = name, age, height
  end

  def inspect
    '#@name #@age #@height'
  end

end

class Array

  def sort_by(sym)
    self.sort {|x,y| x.send(sym) <=> y.send(sym) }
  end

end

people = []
people << Person.new('A', 5, 9)
people << Person.new('B', 2, 4)
people << Person.new('C', 6, 8)
people << Person.new('D', 3, 3)

p1 = people.sort_by(:name)
p2 = people.sort_by(:age)
p3 = people.sort_by(:height)

p p1   
p p2   
p p3   

标签:Ruby,Array

收藏

0人收藏

支持

0

反对

0

发表评论