How to get Ruby Dir#glob to return basenames, not absolute_paths?
-
25-10-2019 - |
سؤال
FakeProfilePictures::Photo.all_large_names_2x
(defined below) returns an array of absolute path names, but when I do Dir["picture_*@2x.*"]
from the correct directory in irb
, I only get the basenames (what I want). What's the best way to get the base names? I know I could do it by adding .map { |f| File.basename(f) }
as shown in the comment, but is there an easier/better/faster/stronger way?
module FakeProfilePictures
class Photo
DIR = File.expand_path(File.join(File.dirname(__FILE__), "photos"))
# ...
def self.all_large_names_2x
@@all_large_names_2x ||= Dir[File.join(DIR, "picture_*@2x.*")] # .map { |f| File.basename(f) }
end
end
end
المحلول
You can do
Dir.chdir(DIR) do
Dir["picture_*@2x.*"]
end
after the block, the original dir is restored.
نصائح أخرى
You could chdir
into DIR
before globbing, but I would just run everything through basename
.
لا تنتمي إلى StackOverflow