【问题标题】:Ruby- accessing elements multidimensional arrayRuby-访问元素多维数组
【发布时间】:2023-03-11 15:20:02
【问题描述】:

谁能帮助我更改/组织log条目的逻辑

input_array = [
  ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"]
  ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"]
  ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"]
  ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"]
  ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"]
  ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]
]

如何访问此数组中的各个元素.. 例如2/6/2014application1

当我执行input_array[1][4] 时,所需的输出是...

"application1" # and not 6 ... its giving me the 4 character in line 1

感谢您的帮助!

【问题讨论】:

  • 什么是line?使用该间距,您的代码无效。
  • 即使你使那个特定的语法有效,你仍然会得到一个字符串而不是数组。

标签: ruby arrays multidimensional-array


【解决方案1】:

也许你的意思是这样的:

input_line = [
  ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"],
  ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"],
  ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"],
  ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"],
  ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"],
  ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]]

?

然后您可以毫无问题地使用语法input_array[i][j]

【讨论】:

  • 是的,你是对的。必须弄清楚如何在每个数组之后获取逗号...谢谢队友
【解决方案2】:

如果您实际上是这样定义数组的,那么您建议的代码有错误:

input_array = [
    ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"],
      ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"],
      ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"],
      ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"],
      ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"],
      ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]
    ]

然后你就可以像这样访问你的数组了:

2.0.0p195 :054 > input_array[0][0]
 => "2/6/2014" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多