Ruby-访问元素多维数组

时间:2014-05-14 02:45:24

标签: ruby arrays multidimensional-array

你能否帮助我改变/组织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

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果您实际定义了这样的数组,那么您提出的代码会出错:

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" 

答案 1 :(得分:0)

也许你的意思是:

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]而不会出现问题!