1

I have input string str ="/Users/user/Desktop/task/U6342_Account_20150112.txt"

and in return I want array ['U6342','Account','20150112']

To get the result what I did

str.split('/')[-1].gsub('.txt','').split('_')

which outputs ['U6342','Account','20150112']

Now my question- Is there any better solution?

1 Answer 1

5

Ruby has a built-in File class for similar cases.

fname = File.basename(str, '.*') # "U6342_Account_20150112"
fname.split('_') # ["U6342", "Account", "20150112"]

Or, in short:

File.basename(str, '.*').split('_')

Edit: the second parameter in basename tells the function what suffix the file has. It supports the * wildcard to match any suffix, and then removes it from the result. Examples:

File.basename(str, '.*') # "U6342_Account_20150112"
File.basename(str, '.txt') # "U6342_Account_20150112"
File.basename(str, '.jpg') # "U6342_Account_20150112.txt" => suffix not removed

Read more here http://ruby-doc.org/core-2.2.0/File.html#method-c-basename

Sign up to request clarification or add additional context in comments.

1 Comment

".*" what does it means?

Your Answer

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.