Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by an array's elements properties in ruby

I have an array of objects which created from a custom class. The custom class have some attributes and i want to sort the array by one of these attributes? Is there an easy way to implement this on ruby, or should i code it from scratch?

Example:

class Example
  attr_accessor :id, :number

  def initialize(iid,no)
    @id = iid
    @number = no
  end
end

exarray = []
1000.times do |n|
  exarray[n] = Example.new(n,n+5)
end

Here i want to sort the exarray by its elements number attribute.

like image 791
gkaykck Avatar asked Feb 20 '11 20:02

gkaykck


2 Answers

sort_by is probably the shortest option

exarray.sort_by {|x| x.number}

This also works

exarray.sort_by &:number
like image 100
Nikita Rybak Avatar answered Sep 21 '22 17:09

Nikita Rybak


If you wish to encapsulate this logic inside the class, implement a <=> method on your class, you can tell Ruby how to compare objects of this type. Here's a basic example:

class Example
  include Comparable  # optional, but might as well
  def <=>(other)
    this.number <=> other.number
  end
end

Now you can call exarray.sort and it will "just work."


Further reading:

  • http://www.ruby-doc.org/core/classes/Array.html#M000244 (Array#sort)
  • http://www.ruby-doc.org/core/classes/Comparable.html
like image 35
wuputah Avatar answered Sep 22 '22 17:09

wuputah