4
\$\begingroup\$

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?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Dec 9, 2015 at 7:46
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

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('_')
janos
113k15 gold badges154 silver badges396 bronze badges
answered Dec 9, 2015 at 8:01
\$\endgroup\$
0
\$\begingroup\$

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.

answered Dec 9, 2015 at 19:23
\$\endgroup\$
2
  • \$\begingroup\$ Flexible? I see only three captures. You probably want recursive regex. \$\endgroup\$ Commented Dec 10, 2015 at 11:31
  • \$\begingroup\$ good point, basically i was just saying regex + captures solves lots of these kinds of problems \$\endgroup\$ Commented Dec 10, 2015 at 15:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.