Sort object array by object attribute : sort « Array « Ruby






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   

 








Related examples in the same category

1.apply the sort (or sort!, for in-place changes)
2.Get the top 5 elements
3.Get the bottom 5 elements
4.ArgumentError: comparison of Fixnum with String failed