【问题标题】:ruby arrays can each_with_index do steps?ruby 数组可以 each_with_index 做步骤吗?
【发布时间】:2013-04-12 15:27:37
【问题描述】:

我有一个 txt 记录文件:

firstname lastname dob ssn status1 status2 status3 status4 firstname lastname dob ...

我可以把它放到一个数组中:

tokens[0] = firstname
...
tokens[8] = firstname (of record 2).  
tokens[9] = lastname (of record 2) and so on.

我想逐步迭代 tokens 数组,所以我可以说:

record1 = tokens[index] + tokens[index+1] + tokens[index+2] etc.

步骤(在上面的示例 8 中)将处理记录:

record2, record3 etc etc.

step 0 index is 0
step 1 (step set to 8 so index is 8)
etc.

我想我应该说这些记录来自我称为 .split 的 txt 文件:

file = File.open(ARGV[0], 'r')
line = ""
while !file.eof?
   line = file.readline
end
##knowing a set is how many fields, do it over and over again.

tokens = line.split(" ")

【问题讨论】:

  • 你能重新编辑你的代码吗?还为您提供 java 代码和预期的输出,它在 Java 中的样子。回答你的斋戒可能会很棒。

标签: ruby parsing text ruby-1.9.3


【解决方案1】:

这有帮助吗?

tokens = (1..80).to_a #just an array
tokens.each_slice(8).with_index {|slice, index|p index; p slice}
#0
#[1, 2, 3, 4, 5, 6, 7, 8]
#1
#[9, 10, 11, 12, 13, 14, 15, 16]
#...

【讨论】:

    【解决方案2】:

    使用each_slice,您还可以将变量分配给块内的字段:

    tokens.each_slice(8) { |firstname, lastname, dob, ssn, status1, status2, status3, status4|
      puts "firstname: #{firstname}"
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 2011-08-04
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2022-07-26
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多