Sorting by an array's elements properties in r

2020-07-09 03:09发布

问题:

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.

回答1:

sort_by is probably the shortest option

exarray.sort_by {|x| x.number}

This also works

exarray.sort_by &:number


回答2:

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


回答3:

Try:

exarray.sort { |a, b| a.number <=> b.number }