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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
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
This topic is locked and can not be replied to.