Robert Klemme
7/26/2007 11:21:00 AM
2007/7/26, Marcin Tyman <m.tyman@interia.pl>:
> Robert Klemme wrote:
> > 2007/7/26, Marcin Tyman <m.tyman@interia.pl>:
> >>
> >> a20
> > Apparently you want to _sort by_ the numeric part. You can extract it
> > with a regular expression like this:
> >
> > irb(main):017:0> a.sort_by {|x| x[/\d+/].to_i }
> > => ["a1", "a2", "a10", "a20"]
> >
> > Kind regards
> >
> > robert
>
>
> I've done it as follows:
>
> arrOfFiles.sort! do |file1, file2|
>
> f1 = file1.slice(/\d+.sql/)
> f1 = f1.slice(/\d+/)
>
> f2 = file2.slice(/\d+.sql/)
> f2 = f2.slice(/\d+/)
>
>
> f1.to_i <=> f2.to_i
> end
Well, if you want to sort in place you could do
irb(main):003:0> %w{a10 a1 a2 a20}.sort! {|*a| a.map{|x|
x[/\d+/].to_i}.inject {|a,b| a<=>b}}
=> ["a1", "a2", "a10", "a20"]
Um, not very readably I guess.
:-)))
Kind regards
robert