Ruby 有 natural_sort_by 方法吗? [英] Is there a natural_sort_by method for Ruby?
问题描述
我有一个包含一堆属性的文件列表.属性之一是文件名,这是我希望对列表进行排序的方式.但是,该列表是这样的:文件名 1、文件名 2、文件名 10、文件名 20.
I have a list of files with a bunch of attributes. One of the attributes is the file name which is how I would like to sort the list. However, the list goes something like this: filename 1, filename 2, filename 10, filename 20.
ruby sort_by 方法产生这个:
The ruby sort_by method produces this:
files = files.sort_by { |file| file.name }
=> [filename 1, filename 10, filename 2, filename 20]
我想要一个更易读的列表,如文件名 1、文件名 2、文件名 10、文件名 20
I would like a more human readable list like filename 1, filename 2, filename 10, filename 20
我找到了 natural_sort gem,但它似乎只能像排序方法一样工作.我需要一些可以指定数组排序依据的东西.
I found the natural_sort gem but it seems to only work like the sort method. I need something where I can specify what to sort the array by.
有什么帮助吗?
推荐答案
只要文件总是命名为 "file #"
,你就可以做到
As long as files are always named "file #"
, you could do
files.sort_by{|f|f.name.split(" ")[1].to_i }
这会在空间上进行拆分,并抓取数字进行排序.
This splits on the space, and grabs the number to do the sorting.
这篇关于Ruby 有 natural_sort_by 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!