In Ruby what is the right way to get all the files in the directory with a certain extension regardless of the extension case?
For example, say I have the directory ~/myDir
and it has files file1.JPG
, file2.jpg
, noFile.png
and file3.jpg
. I would like to grab only the jpg files. I was using:
results = Dir[File.join(Dir.home, 'myDir', '*.jpg')].sort
but this leaves off file1
.
I don't want a hacky solution like checking the files individually while forcing each to uppercase before checking. I definitely do not want something nasty like grabbing the files with extensions JPG
, JPg
, Jpg
, jpg
, jpG
, and jPG
.
Please include the supported version in your answers if it isn't backward-compatible with older version. I am on 1.9.3
but others may not be.
We can use Dir.glob
and pass it File::FNM_CASEFOLD
as the second param to tell it to ignore the case. So that gives us:
Dir.glob(File.join(Dir.home, 'myDir', "*.jpg"), File::FNM_CASEFOLD).sort
I found this solution in this post where Derick Bailey talks about this post.
I am not sure if it works in all version but if anyone knows let me know and I will update it here. Trans in the last link in this post makes it seem like it wasn't always supported by saying "the docs said '(so+File::FNM_CASEFOLD+ is ignored)' ".