Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/17354864/ruby-filter-array-by-regex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...