List of directory.

M

Marcin Tyman

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
 
R

Robert Klemme

2007/7/26 said:
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

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
 
M

Marcin Tyman

Robert said:
2007/7/26 said:
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
 
R

Robert Klemme

2007/7/26 said:
Robert said:
2007/7/26 said:
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
 
P

Phrogz

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,314
Members
47,993
Latest member
Meri511146

Latest Threads

Top