字符串为ex="test1, test2, test3, test4, test5"
当我使用
ex.split(",").first
它返回
"test1"
现在我想获取剩余的项,即`"test2,test3,test4,test5“。如果我使用
ex.split(",").last
它只返回
"test5"
如何获得所有剩余的项目跳过第一个项目?
发布于 2009-08-26 09:10:43
试试这个:
first, *rest = ex.split(/, /)
现在first
将是第一个值,rest
将是数组的其余部分。
发布于 2009-08-26 09:36:48
ex.split(',', 2).last
结尾处的2表示:分成2部分,而不是更多。
通常情况下,split会将值分割为尽可能多的块,使用第二个值可以限制将获得的块的数量。使用ex.split(',', 2)
将为您提供:
["test1", "test2, test3, test4, test5"]
作为数组,而不是:
["test1", "test2", "test3", "test4", "test5"]
发布于 2009-08-26 09:16:14
你可能打错了几个字。从我收集到的信息来看,您可以从如下字符串开始:
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
这回答了你的问题吗?
https://stackoverflow.com/questions/1333347
复制相似问题