在Ruby中按数组的元素属性排序 [英] Sorting by an array's elements properties in ruby

查看:96
本文介绍了在Ruby中按数组的元素属性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从自定义类创建的对象数组.自定义类具有一些属性,我想按这些属性之一对数组进行排序?是否有一种简单的方法可以在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?

示例:

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

在这里,我想按其元素number属性对exarray进行排序.

Here i want to sort the exarray by its elements number attribute.

推荐答案

sort_by 可能是最短的选项

exarray.sort_by {|x| x.number}

这也可以

exarray.sort_by &:number

这篇关于在Ruby中按数组的元素属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆