List of directory

Hi,

Does anybody know how to list directory in alphabetical order? i.e.
I have following files:
a10
a1
a2
a20

sort method sorts them as follows:

a1
a10
a2
a20

but I need such order:

a1
a2
a10
a20

Any help would be helpful.
Thanks in advance

···

--
Posted via http://www.ruby-forum.com/.

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

···

2007/7/26, Marcin Tyman <m.tyman@interia.pl>:

Hi,

Does anybody know how to list directory in alphabetical order? i.e.
I have following files:
a10
a1
a2
a20

sort method sorts them as follows:

a1
a10
a2
a20

but I need such order:

a1
a2
a10
a20

files = %w| a1 ab1a ab1b ac1 a2 ab2 ab3 b1 bb1 ba1 a10 a20 a10a a aa
ab ac |
puts files.sort_by{ |f|
  f.split( /(\d+)/ ).map{ |piece|
    Integer(piece) rescue piece
  }
}

#=> a
#=> a1
#=> a2
#=> a10
#=> a10a
#=> a20
#=> aa
#=> ab
#=> ab1a
#=> ab1b
#=> ab2
#=> ab3
#=> ac
#=> ac1
#=> b1
#=> ba1
#=> bb1

···

On Jul 26, 4:54 am, Marcin Tyman <m.ty...@interia.pl> wrote:

Does anybody know how to list directory in alphabetical order? i.e.
I have following files:
a10
a1
a2
a20

sort method sorts them as follows:

a1
a10
a2
a20

but I need such order:

a1
a2
a10
a20

Robert Klemme wrote:

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

Thanks Robert

···

2007/7/26, Marcin Tyman <m.tyman@interia.pl>:

--
Posted via http://www.ruby-forum.com/\.

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

···

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