Ruby/Array/sort

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

apply the sort (or sort!, for in-place changes)

x = [ 2, 5, 1, 7, 23, 99, 14, 27 ]
x.sort! # => [1, 2, 5, 7, 14, 23, 27, 99]



ArgumentError: comparison of Fixnum with String failed

[1, 2, 3, "a", "b", "c"].sort



Get the bottom 5 elements

l = [1, 60, 21, 100, -5, 20, 60, 22, 85, 91, 4, 66]
sorted = l.sort
# The bottom 5
p sorted[0...5]
# => [-5, 1, 4, 20, 21]



Get the top 5 elements

l = [1, 60, 21, 100, -5, 20, 60, 22, 85, 91, 4, 66]
sorted = l.sort
# The top 5
p sorted[-5...sorted.size]
# => [60, 66, 85, 91, 100]



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