0
0

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 : ファイルの標準入出力について

Last updated at Posted at 2020-05-13

ファイルをリダイレクトで標準入力する

$ ruby example.rb < sample1.txt

ファイルをリダイレクトで標準出力する

$ ruby example.rb > sample2.txt

pまたはputsで出力した結果がファイルに保存される。

ファイルのリダイレクトによる標準入出力を同時に行う

$ ruby example.rb < sample1.txt > sample2.txt

標準入力で受け取ったファイルの内容を1行ずつ表示する

  • 対象ファイル
meibo.txt
john	m	18
paul	m	20
alice	f	15
dabid	m	17
jasmin	f	17
  • rubyプログラム
example1.rb
while line = gets
  p line
end
  • 出力結果
$ ruby example1.rb < meibo.txt
"john\tm\t18\n"
"paul\tm\t20\n"
"alice\tf\t15\n"
"dabid\tm\t17\n"
"jasmin\tf\t17"

標準入力で受け取ったcsvファイルの内容を1行ずつ表示する

  • 対象ファイル
meibo.csv
"john","m","18"
"paul","m","20"
"alice","f","15"
"dabid","m","17"
"jasmin","f","17"
  • rubyプログラム
example2.rb
require 'csv'

CSV(STDIN).each do |line|
  p line
end
  • 出力結果
$ ruby example2.rb < meibo.csv
["john", "m", "18"]
["paul", "m", "20"]
["alice", "f", "15"]
["dabid", "m", "17"]
["jasmin", "f", "17"]

結果は配列で返ってくる。

標準入力で受け取ったjsonファイルの内容を1行ずつ表示する

  • 対象ファイル
meibo.json
[{"name":"john","gender":"m","age":"18"},
 {"name":"paul","gender":"m","age":"20"},
 {"name":"alice","gender":"f","age":"15"},
 {"name":"dabid","gender":"m","age":"17"},
 {"name":"jasmin","gender":"f","age":"17"}]
  • rubyプログラム
example3.rb
require 'json'

people = JSON.parse(STDIN.read)

people.each do |person|
  p person
end
  • 出力結果
$ ruby sample3.rb < meibo.json 
{"name"=>"john", "gender"=>"m", "age"=>"18"}
{"name"=>"paul", "gender"=>"m", "age"=>"20"}
{"name"=>"alice", "gender"=>"f", "age"=>"15"}
{"name"=>"dabid", "gender"=>"m", "age"=>"17"}
{"name"=>"jasmin", "gender"=>"f", "age"=>"17"}

結果はhashで返ってくる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?