3
2

More than 5 years have passed since last update.

Ruby でテキストファイルを2行ずつ処理する

Posted at

Enumerable#each_slice

指定した数ずつ処理することができる Enumerable#each_slice が用意されている。

instance method Enumerable#each_slice (Ruby 2.4.0) https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/each_slice.html

n 要素ずつブロックに渡して繰り返します。
要素数が n で割り切れないときは、最後の回だけ要素数が減ります。
ブロックを省略した場合は n 要素ずつ繰り返す Enumerator を返します。

テキストファイルを2行ずつ処理する

サンプルコード。

# 2行ずつ処理する
File.open(ARGV[0]) do |file|
  file.each_slice(2) do |lines|
    puts "class: #{lines.class}"
    puts "size: #{lines.size}"
    puts "1: #{lines[0]}"
    puts "2: #{lines[1]}"
  end
end

処理用のサンプルとして、5行のテキストファイルを用意。

Alice
Bob
Carol
Dave
Ellen

実行結果。
ブロックに渡されるのは Array オブジェクト。

class: Array
size: 2
1: Alice
2: Bob
class: Array
size: 2
1: Carol
2: Dave
class: Array
size: 1
1: Ellen
2: 

テキストファイルを3行ずつ処理する

each_slice メソッドに指定する数を3にするだけで3つずつ処理できる。

# 3行ずつ処理する
File.open(ARGV[0]) do |file|
  file.each_slice(3) do |lines|
    puts "1: #{lines[0]}"
    puts "2: #{lines[1]}"
    puts "3: #{lines[2]}"
  end
end
3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2