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.
sort_by is probably the shortest option
exarray.sort_by {|x| x.number}
This also works
exarray.sort_by &:number
                        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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With