Sorting by an array's elements properties in r

2020-07-09 03:05发布

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.

3条回答
来,给爷笑一个
2楼-- · 2020-07-09 03:18

Try:

exarray.sort { |a, b| a.number <=> b.number }
查看更多
家丑人穷心不美
3楼-- · 2020-07-09 03:21

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:

查看更多
我想做一个坏孩纸
4楼-- · 2020-07-09 03:31

sort_by is probably the shortest option

exarray.sort_by {|x| x.number}

This also works

exarray.sort_by &:number
查看更多
登录 后发表回答