sgi*_*sgi 80 ruby string split
字符串是
ex="test1, test2, test3, test4, test5"
我用的时候
ex.split(",").first
Run Code Online (Sandbox Code Playgroud)
它返回
"test1"
Run Code Online (Sandbox Code Playgroud)
现在我想得到剩下的项目,即`"test2,test3,test4,test5".如果我使用
ex.split(",").last
Run Code Online (Sandbox Code Playgroud)
它只返回
"test5"
Run Code Online (Sandbox Code Playgroud)
如何让所有剩余的项目首先跳过?
avd*_*aag 96
试试这个:
first, *rest = ex.split(/, /)
Run Code Online (Sandbox Code Playgroud)
现在first将是第一个值,rest将是数组的其余部分.
use*_*365 42
ex.split(',', 2).last
Run Code Online (Sandbox Code Playgroud)
最后的2说:分成2件,而不是更多.
通常拆分会将值切割成尽可能多的碎片,使用第二个值可以限制您将获得的碎片数量.使用ex.split(',', 2)会给你:
["test1", "test2, test3, test4, test5"]
Run Code Online (Sandbox Code Playgroud)
作为一个数组,而不是:
["test1", "test2", "test3", "test4", "test5"]
Run Code Online (Sandbox Code Playgroud)
Kon*_*lph 14
既然你有阵列,你真正想要的Array#slice不是split.
rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]
Run Code Online (Sandbox Code Playgroud)
你可能输错了一些东西.从我收集的内容开始,您可以使用以下字符串:
string = "test1, test2, test3, test4, test5"
Run Code Online (Sandbox Code Playgroud)
然后你想要拆分它只保留重要的子串:
array = string.split(/, /)
Run Code Online (Sandbox Code Playgroud)
最后,您只需要除第一个元素之外的所有元素:
# We extract and remove the first element from array
first_element = array.shift
# Now array contains the expected result, you can check it with
puts array.inspect
Run Code Online (Sandbox Code Playgroud)
这回答了你的问题吗?
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
Run Code Online (Sandbox Code Playgroud)
如果你想将它们用作你已经知道的数组,那么你可以将它们中的每一个用作不同的参数...试试这个:
parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
Run Code Online (Sandbox Code Playgroud)
对不起有点迟到的派对,有点惊讶,没有人提到drop方法:
ex="test1, test2, test3, test4, test5"
ex.split(",").drop(1).join(",")
=> "test2,test3,test4,test5"
Run Code Online (Sandbox Code Playgroud)