Ruby: filter array by regex? Ruby: filter array by regex? arrays arrays

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"]]


Have a look at Enumerable.grep, it's a very powerful way of finding/filtering things in anything enumerable.


$ cat foo.rbimages = %w[foo.gif foo.png foo.jpg bar.jpeg moo.JPG]jpgs = images.select{|e| e =~ /\.jpe?g$/i}puts jpgs.inspect$ ruby foo.rb["foo.jpg", "bar.jpeg", "moo.JPG"]

The change to your regexp is so that you can match "jpeg" in addition to "jpg" regardless of case.