Reputation: 111
I have a FileList
with *.js
and *.tc
extensions. How can I split it into two arrays of FileList
, one with only *.js
files and the other with *.tc
files?
Upvotes: 1
Views: 379
Reputation: 121000
Enumerable#partition
comes to the rescue.
["aaa.js", "bbb.js", "ccc.js",
"xxx.tc", "yyy.tc", "zzz.tc" ].partition do |e|
e[/(?<=\.).*\z/] == "tc"
end
#⇒ [["xxx.tc", "yyy.tc", "zzz.tc"],
# ["aaa.js", "bbb.js", "ccc.js"]]
or, more explicit:
["aaa.js", "bbb.js", "ccc.js",
"xxx.tc", "yyy.tc", "zzz.tc" ].partition(&/\.tc\z/.method(:=~))
Upvotes: 2
Reputation: 34308
You can use File.extname
to get the extension of a file name, and Array#group_by
to group array members with similarities:
result = [ "aaa.js", "bbb.js", "ccc.js",
"xxx.tc", "yyy.tc", "zzz.tc" ].group_by { |fname| File.extname(fname) }
=> { ".js" => ["aaa.js", "bbb.js", "ccc.js"],
".tc" => ["xxx.tc", "yyy.tc", "zzz.tc"] }
Now you have a Hash
containing two arrays (result[".js"]
and result[".tc"]
) that contain the file names according to their extensions.
Upvotes: 4