【问题标题】:How to split a string in Ruby and get all items except the first one?如何在Ruby中拆分字符串并获取除第一个之外的所有项目?
【发布时间】:2010-11-22 22:21:18
【问题描述】:

字符串是 ex="test1, test2, test3, test4, test5"

当我使用时

ex.split(",").first

它返回

"test1"

现在我想获取剩余的项目,即“test2,test3,test4,test5”。如果我使用

ex.split(",").last

它只返回

"test5"

如何让所有剩余的项目跳过第一个?

【问题讨论】:

  • 等等,你在Array上使用splitString方法)?
  • sorry guyzz...我在这里使用字符串.. 我将编辑问题

标签: ruby string split


【解决方案1】:

试试这个:

first, *rest = ex.split(/, /)

现在first 将是第一个值,rest 将是数组的其余部分。

【讨论】:

  • Ruby 的哪个版本?我在 1.8.7 中尝试过,rest 只包含“test2”。
  • 大概意思是first,*rest = ex.split(/,/)
  • 是的,当时我无法测试我的生产线。 first, *rest = ex.split(/,/) 确实是我的意思。感谢您清除它。
  • 另一种方法是从结果数组中获取范围。 things = ex.split(/,/); things[1..-1]
【解决方案2】:
ex.split(',', 2).last

最后的2说:分成2块,不多。

通常 split 会将值切割成尽可能多的部分,使用第二个值可以限制您将获得的部分。使用ex.split(',', 2) 会给你:

["test1", "test2, test3, test4, test5"]

作为一个数组,而不是:

["test1", "test2", "test3", "test4", "test5"]

【讨论】:

  • 如果您想要除第一个值以外的所有值作为数组而不是字符串,则必须再次split。仍然是一个不错的技巧。另外,使用ex.split(',', 2).last 不会返回你提到的数组,只返回它的最后一个值,对吧?
  • 复制粘贴错误哈哈,修复了
【解决方案3】:

既然你有一个数组,那么你真正想要的是Array#slice,而不是split

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]

【讨论】:

  • 因此,如果您对第一个值不感兴趣,那么您希望 ex.split(/, /).slice(1..-1) 获取除第一个元素之外的所有元素。
【解决方案4】:

你可能打错了一些东西。根据我收集的信息,您从一个字符串开始,例如:

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

这回答了你的问题吗?

【讨论】:

    【解决方案5】:

    很抱歉聚会晚了,有点惊讶没有人提到drop 方法:

    ex="test1, test2, test3, test4, test5"
    ex.split(",").drop(1).join(",")
    => "test2,test3,test4,test5"
    

    【讨论】:

      【解决方案6】:
      ex="test1,test2,test3,test4,test5"
      all_but_first=ex.split(/,/)[1..-1]
      

      【讨论】:

        【解决方案7】:

        如果您想将它们用作您已经知道的数组,否则您可以将它们中的每一个用作不同的参数... 试试这个:

        parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
        

        【讨论】:

          【解决方案8】:

          您也可以这样做:

          String is ex="test1, test2, test3, test4, test5"
          array = ex.split(/,/)
          array.size.times do |i|
            p array[i]
          end 
          

          【讨论】:

            【解决方案9】:

            尝试split(",")[i],其中i 是结果数组中的索引。 split 在下面给出数组

            ["test1", " test2", " test3", " test4", " test5"] 
            

            可以通过索引访问其元素。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-10-05
              • 1970-01-01
              • 2023-03-28
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多