LoginSignup
0
0

Ruby芸160チャレンジ(#5)スペース区切りのフィールドを持つテキストファイルの扱い

Last updated at Posted at 2023-12-04

この記事は何

shellgei160を通じて言語習得 Advent Calendar 2023に参加しています。

書籍「シェル芸ワンライナー160本ノック」の例題をRubyで解いてみて、Rubyの学習に役立てようとするものです。

例題はこちらのリポジトリで公開されているものに限ります。
https://github.com/shellgei/shellgei160

実行環境など

  • Docker image: ruby:3.0.2
  • 上記リポジトリをクローンした上で、リポジトリのルートディレクトリ直下にanswer-rubyディレクトリを作り、その中に解答となるファイルを作成していきます。

今回のテーマ

$ cat ntp.conf | awk '$1=="pool"' | awk '{print $2}'

ntp.conf内で1番目のフィールドがpoolの行について2番目のフィールドを表示します。

lines = File.open('./qdata/5/ntp.conf').readlines

lines.each do |line|
  fields = line.split(' ')
  next if fields.size < 2

  puts fields[1] if fields[0] == 'pool'
end

所感

  • 特になし
0
0
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
0
0