Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Ruby Dir#glob to return basenames, not absolute_paths?

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
like image 450
ma11hew28 Avatar asked Apr 27 '11 21:04

ma11hew28


2 Answers

You can do

Dir.chdir(DIR) do
  Dir["picture_*@2x.*"]
end

after the block, the original dir is restored.

like image 154
J-_-L Avatar answered Nov 06 '22 06:11

J-_-L


You could chdir into DIR before globbing, but I would just run everything through basename.

like image 42
cam Avatar answered Nov 06 '22 07:11

cam