Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group strings with similar pattern in Ruby

I have an array of filenames. A subset of these may have similar pattern like this (alphabet strings with a number at the end):

arr = %w[
  WordWord1.html
  WordWord3.html
  WordWord10.html
  WordWord11.html
  AnotherWord1.html
  AnotherWord2.html
  FileFile.html
]

How to identify the similar ones (they have identical substring, just their numbers differ) and move them to an array ?

['WordWord1.html', 'WordWord3.html', 'WordWord10.html', 'WordWord11.html']
['AnotherWord1.html', 'AnotherWord2.html']
['FileFile.html']
like image 723
Lamnk Avatar asked Mar 20 '26 16:03

Lamnk


2 Answers

arr.group_by { |x| x[/[a-zA-Z]+/] }.values
like image 159
fgb Avatar answered Mar 23 '26 07:03

fgb


filenames = ["WordWord1.html", "WordWord3.html", "WordWord10.html", "WordWord11.html", "AnotherWord1.html", "AnotherWord2.html", "FileFile.html"]
filenames.inject({}){|h,f|k = f.split(/[^a-zA-Z]/, 2).first;h[k] ||= [];h[k] << f; h}
like image 34
Ian Avatar answered Mar 23 '26 06:03

Ian