25
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby で今読み込んでいるファイルの行数を取得する

Posted at

読み込んでいるファイルの行数は File#lineno を使えば取得できるのだが、けっこう忘れがち。

data.txt
hoge
huga
piyo
open("data.txt") {|f|
  f.each_line do |line|
    line.chomp!
    puts "#{f.lineno}: #{line}"
  end
}
# >> 1: hoge
# >> 2: huga
# >> 3: piyo

f.lines.each_with_index も使えなくはないが、こちらは1行目を0と数えるので適宜使いわけるといい。

行数取得のために一時変数をループの度にインクリメントしていたような人は是非覚えておこう。

25
22
0

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
25
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?