Forum: Ruby check if file exists for part of the filename

A40ea9c816d41de88a806fecfaf1afb6?d=identicon&s=25 Christian Kerth (kerthi)
on 2008-03-14 09:33
Hey!

How do i check if a file exists, that starts with a certain identifier?

e.g. Files in Directory

file_1.rb
file_2.rb
test_1.rb

I only want to know if a file exists, that starts with "file_"

thx
9a56d606d07692444b1e60635eb22df8?d=identicon&s=25 Mark Bush (bush)
on 2008-03-14 10:02
Christian Kerth wrote:
> I only want to know if a file exists, that starts with "file_"

Dir.entries('.').detect {|f| f.match /^file_/}

Replace '.' with the name of the directory to check if it is not the
current directory.  Will return the name of the first file to match if
there is one, else will return nil.
6087a044557d6b59ab52e7dd20f94da8?d=identicon&s=25 Peña, Botp (Guest)
on 2008-03-14 10:05
(Received via mailing list)
[mailto:list-bounce@example.com] On Behalf Of Christian Kerth
# How do i check if a file exists, that starts with a certain
# identifier?
# e.g. Files in Directory
# file_1.rb
# file_2.rb
# test_1.rb
# I only want to know if a file exists, that starts with "file_"

there are many ways.
these are just some...

Dir.glob("file_*.rb").empty?
#=> false

Dir.glob("file_*.rb").size>0
#=> true

Dir.glob("file_*.rb")
#=> ["file_1.rb", "file_2.rb", "file_3.rb"]

File.exist? "file_1.rb"
#=> true

File.exist? "file_2.rb"
#=> true

File.exist? "file_4.rb"
#=> false


kind regards -botp
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.