Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: filter array by regex?

This is a common, repetitive idiom for me: filtering an array using a regular expression, and returning a sub-array. My approach doesn't seem very Ruby-like (I come from Java). I end up having many methods which look a lot like this.

What is the idiomatic Ruby way to improve this code?

def get_all_gifs(items_)   output = Array.new   filter = /\.jpg$/   items_.each do |item|     next if item =~ filter     output << item   end   output end 
like image 804
aljabear Avatar asked Jun 27 '13 23:06

aljabear


2 Answers

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"]] 
like image 126
the Tin Man Avatar answered Sep 27 '22 20:09

the Tin Man


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

like image 22
steenslag Avatar answered Sep 27 '22 22:09

steenslag