[英]How to split a string in Ruby and get all items except the first one?
字符串是ex="test1, test2, test3, test4, test5"
我用的时候
ex.split(",").first
它返回
"test1"
现在我想得到剩下的项目,即`“test2,test3,test4,test5”。 如果我使用
ex.split(",").last
它只返回
"test5"
如何让所有剩余的项目首先跳过?
试试这个:
first, *rest = ex.split(/, /)
现在first
是第一个值, rest
将是数组的其余部分。
ex.split(',', 2).last
最后的2说:分成2件,而不是更多。
通常拆分会将值切割成尽可能多的碎片,使用第二个值可以限制您将获得的碎片数量。 使用ex.split(',', 2)
将为您提供:
["test1", "test2, test3, test4, test5"]
作为一个数组,而不是:
["test1", "test2", "test3", "test4", "test5"]
既然你有一个数组,你真正想要的是Array#slice
,而不是split
。
rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]
你可能输错了一些东西。 从我收集的内容开始,您可以使用以下字符串:
string = "test1, test2, test3, test4, test5"
然后你想要拆分它只保留重要的子串:
array = string.split(/, /)
最后,您只需要除第一个元素之外的所有元素:
# 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
这回答了你的问题吗?
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
如果你想将它们用作你已经知道的数组,那么你可以将它们中的每一个用作不同的参数...试试这个:
parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
对不起有点迟到的派对,有点惊讶,没有人提到drop方法:
ex="test1, test2, test3, test4, test5"
ex.split(",").drop(1).join(",")
=> "test2,test3,test4,test5"
你也可以这样做:
String is ex="test1, test2, test3, test4, test5"
array = ex.split(/,/)
array.size.times do |i|
p array[i]
end
尝试split(",")[i]
其中i
是结果数组中的索引。 split
给出了下面的数组
["test1", " test2", " test3", " test4", " test5"]
其元素可以通过索引访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.