[英]Ruby parse string and return array
I have input string str ="/Users/user/Desktop/task/U6342_Account_20150112.txt"
我输入了字符串
str ="/Users/user/Desktop/task/U6342_Account_20150112.txt"
and in return I want array ['U6342','Account','20150112']
作为回报,我想要数组
['U6342','Account','20150112']
To get the result what I did 为了得到我所做的结果
str.split('/')[-1].gsub('.txt','').split('_')
which outputs ['U6342','Account','20150112']
输出
['U6342','Account','20150112']
Now my question- Is there any better solution? 现在我的问题是-有更好的解决方案吗?
Ruby has a built-in File class for similar cases. Ruby在类似情况下具有内置的File类。
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. 编辑:
basename
的第二个参数告诉函数文件有什么后缀。 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 在此处阅读更多信息http://ruby-doc.org/core-2.2.0/File.html#method-c-basename
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.