I have a string str ="/Users/user/Desktop/task/U6342_Account_20150112.txt"
I need return only U6342_Account_20150112
as an array ['U6342','Account','20150112']
I did
str.split('/')[-1].gsub('.txt','').split('_')
which gives me ['U6342','Account','20150112']
Is there any more convenient solution to do it?
2 Answers 2
The string looks like a filename, so you should use the library functions for handling file paths instead of rolling your own.
File.basename(str, '.txt').split('_')
I really like 200_success's answer, and that's what I'd use for this specific situation, but here's an alternative that's flexible for other situations, using a regexp:
str.match(/([^\/_]+)_([^_]+)_([^_]+).txt/).captures
Each piece you want is captured by a parentheses group, and we turn it into the array you want by calling captures
on the match result.
-
\$\begingroup\$ Flexible? I see only three captures. You probably want recursive regex. \$\endgroup\$Nakilon– Nakilon2015年12月10日 11:31:19 +00:00Commented Dec 10, 2015 at 11:31
-
\$\begingroup\$ good point, basically i was just saying regex + captures solves lots of these kinds of problems \$\endgroup\$Jonah– Jonah2015年12月10日 15:42:35 +00:00Commented Dec 10, 2015 at 15:42