[英]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? 有没有一种简单的方法在ruby上实现它,或者我应该从头开始编码?
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. 在这里,我想通过其元素number
属性对exarray进行排序。
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. 如果您希望将此逻辑封装在类中,请在类上实现<=>
方法,您可以告诉Ruby如何比较此类对象。 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." 现在你可以调用exarray.sort
,它将“正常工作”。
Further reading: 进一步阅读:
尝试:
exarray.sort { |a, b| a.number <=> b.number }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.