在二维数组中注入增量计数器

时间:2014-12-07 00:06:51

标签: ruby arrays algorithm matrix data-structures

拥有这种矩阵结构:

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]]

1 个答案:

答案 0 :(得分:1)

这样做:

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) }