如何在 Ruby 中做到这一点?

发布于 2024-09-07 18:16:58 字数 374 浏览 2 评论 0原文

我在 ruby​​ 中有一个数组(列表?):

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"]

我需要对此运行一个循环以获取一个列表,该列表将元素从“开始”直到遇到另一个“开始”,如下所示:

listOfRows = [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]]

I have an array(list?) in ruby:

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"]

I need to run a loop on this to get a list that clubs elements from "start" till another "start" is encountered, like the following:

listOfRows = [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

も让我眼熟你 2024-09-14 18:16:58

基于 Array#split

def group(arr, bookend)
  arr.inject([[]]) do |results, element|
    if (bookend == element)
      results << []
    end
    results.last << element

    results
  end.select { |subarray| subarray.first == bookend } # if the first element wasn't "start", skip everything until the first occurence
end

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"]
listOfRows = group(allRows, "start")
# [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]]

Based on Array#split from Rails:

def group(arr, bookend)
  arr.inject([[]]) do |results, element|
    if (bookend == element)
      results << []
    end
    results.last << element

    results
  end.select { |subarray| subarray.first == bookend } # if the first element wasn't "start", skip everything until the first occurence
end

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"]
listOfRows = group(allRows, "start")
# [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]]
你爱我像她 2024-09-14 18:16:58

如果您可以使用 ActiveSupport(例如,在 Rails 内部):

def groups(arr, delim)
  dels = arr.select {|e| == delim }
  objs = arr.split(delim)

  dels.zip(objs).map {|e,objs| [e] + objs }
end

If you can use ActiveSupport (for example, inside Rails):

def groups(arr, delim)
  dels = arr.select {|e| == delim }
  objs = arr.split(delim)

  dels.zip(objs).map {|e,objs| [e] + objs }
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文