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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With