Ruby: filter array by regex?

If you want to find all gifs:

def get_all_gifs(files)
  files.select{ |i| i[/\.gif$/] }
end

If you want to find all jpegs:

def get_all_jpgs(files)
  files.select{ |i| i[/\.jpe?g$/] }
end

Running them:

files = %w[foo.gif bar.jpg foo.jpeg bar.gif]
get_all_gifs(files) # => ["foo.gif", "bar.gif"]
get_all_jpgs(files) # => ["bar.jpg", "foo.jpeg"]

But wait! There’s more!

What if you want to group them all by their type, then extract based on the extension?:

def get_all_images_by_type(files)
  files.group_by{ |f| File.extname(f) }
end

Here’s the types of files:

get_all_images_by_type(files).keys # => [".gif", ".jpg", ".jpeg"]

Here’s how to grab specific types:

get_all_images_by_type(files) # => {".gif"=>["foo.gif", "bar.gif"], ".jpg"=>["bar.jpg"], ".jpeg"=>["foo.jpeg"]}
get_all_images_by_type(files)['.gif'] # => ["foo.gif", "bar.gif"]
get_all_images_by_type(files).values_at('.jpg', '.jpeg') # => [["bar.jpg"], ["foo.jpeg"]]

Leave a Comment