[["IssueComment-6ren">
gpt4 book ai didi

ruby - 在二维数组中注入(inject)增量计数器

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:24:49 24 4
gpt4 key购买 nike

具有这种矩阵结构:

irb(main):026:0> data["rows"].flatten.map{|c1|c1["f"].map{|c2|c2["v"]}}
=> [["IssueCommentEvent", "369"], ["WatchEvent", "2217"], ["IssuesEvent", "65"], ["ForkEvent", "136"], ["PushEvent", "51"], ["PullRequestReviewCommentEvent", "69"], ["PullRequestEvent", "116"], ["PublicEvent", "1"], ["CommitCommentEvent", "9"]]
irb(main):027:0>

如何将增量计数器添加为最内层数组的元素?

想要的结果:

[["1", "IssueCommentEvent", "369"], ["2", "WatchEvent", "2217"], ["3", "IssuesEvent", "65"], ["4", "ForkEvent", "136"], ["5", "PushEvent", "51"], ["6", "PullRequestReviewCommentEvent", "69"], ["7", "PullRequestEvent", "116"], ["8", "PublicEvent", "1"], ["9", "CommitCommentEvent", "9"]]

我尝试了以下方法,但它破坏了结构,增加了一个维度:

irb(main):033:0>data["rows"].flatten.map{|c1|c1["f"].map{|c2|c2["v"]}}.map.with_index(1).to_a
=> [[["IssueCommentEvent", "369"], 1], [["WatchEvent", "2217"], 2], [["IssuesEvent", "65"], 3], [["ForkEvent", "136"], 4], [["PushEvent", "51"], 5], [["PullRequestReviewCommentEvent", "69"], 6], [["PullRequestEvent", "116"], 7], [["PublicEvent", "1"], 8], [["CommitCommentEvent", "9"], 9]]

最佳答案

这样做就可以了:

arr = [
["IssueCommentEvent", "369"], ["WatchEvent", "2217"],
["IssuesEvent", "65"], ["ForkEvent", "136"],
["PushEvent", "51"], ["PullRequestReviewCommentEvent", "69"],
["PullRequestEvent", "116"], ["PublicEvent", "1"],
["CommitCommentEvent", "9"]]

arr.map.with_index(1) { |a,i| [i.to_s] + a }
#=> [["1", "IssueCommentEvent", "369"],
# ["2", "WatchEvent", "2217"],
# ...
# ["9", "CommitCommentEvent", "9"]]

如果你更喜欢修改arr,那么使用:

arr.map.with_index(1) { |a,i| a.unshift(i.to_s) }

关于ruby - 在二维数组中注入(inject)增量计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com