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.
Try:
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:Now you can call
exarray.sort
and it will "just work."Further reading:
sort_by is probably the shortest option
This also works