Gregory Seidman
10/30/2008 10:31:00 PM
On Fri, Oct 31, 2008 at 06:14:51AM +0900, Li Chen wrote:
> Hi,
>
> I have an array containing files names. How do I sort them so that I can
> get the expected results?
>
> Thanks,
>
> Li
>
> #############
> files=[
> "c:/ruby/self/2004/20.txt",
> "c:/ruby/self/2004/3.txt",
> "c:/ruby/self/2004/2.txt",
> "c:/ruby/self/2004/10.txt",
> "c:/ruby/self/2004/1.txt"
> ]
>
> expected results:
> [
> "c:/ruby/self/2004/1.txt",
> "c:/ruby/self/2004/2.txt",
> "c:/ruby/self/2004/3.txt",
> "c:/ruby/self/2004/10.txt",
> ]
> "c:/ruby/self/2004/20.txt",
files = files.sort_by { |f| f[/\/(\d+)\.[^\/]*\Z/, 1].to_i }
There are several things to explain here:
- The #sort_by method calls the block on each element to produce a set of
surrogate values to use as sorting keys.
- The regular expression captures the series of digits between the last
slash in a string and the following dot.
- The [] method can be called on String in many ways, including passing a
RegExp and an index. That form returns the capture of the appropriate
index from matching the RegExp or nil if the RegExp does not match.
- Calling #to_i on the result means that it will either parse the captured
sequence of digits as an integer or, if the RegExp fails, return 0.
--Greg