Alexander Shmatko Alexander Shmatko - 6 months ago 12
Ruby Question

How to get file with greatest number in filename within directory?

Consider I have a directory with the following files:

20151203073208_create_animals.rb
20151214130905_create_spoons.rb
20151230083444_create_cups.rb
20160226120137_create_humans.rb
20160321204759_create_trees.rb


I need to get these digits 20160321204759.

However finding the last modified file doesn't apply here as any file withing the directory can be modified last.

For example:

Dir.glob(Rails.root.join('db/migrate/**.*')).max_by {|f| File.mtime(f)}


produces

20151214130905_create_spoons.rb


So how can I get number from filename with the greatest digits?

Answer

To find all migrations:

Dir['db/migrate/**/[0-9]*_*.rb']
#=> ["20151203073208_create_animals.rb",
#    "20151214130905_create_spoons.rb",
#    "20151230083444_create_cups.rb",
#    "20160226120137_create_humans.rb",
#    "20160321204759_create_trees.rb"]

The one with the largest timestamp:

Dir['db/migrate/**/[0-9]*_*.rb'].max
#=> "20160321204759_create_trees.rb"

Just the timestamp:

Dir['db/migrate/**/[0-9]*_*.rb'].max[/\d+/]
#=> "20160321204759"

Of course, you can also use Dir.glob instead of Dir.[] and Rails.root instead of a relative path name.