LoginSignup
0
0

More than 5 years have passed since last update.

crystalで標準入力を受け取ってみる

Last updated at Posted at 2017-07-21

STDINを取得したい

競技プログラミングでよくある入力はUNIXで言うところの標準入力に値が入っている状態だ。なのでSTDINから値を取り出したい。

  • パイプだとこんな感じのイメージ
$ echo "input-text" | ruby main.rb

STDIN.raw でやってみる

  • ドキュメントを見るとこれでよさそうなのだが、#raw メソッドがターミナル(tty)を開いてないと動かない仕様なのでダメ
    • can't set IO#raw: Inappropriate ioctl for device のようなエラーが出る
    • io/console.cr#L79 曰く Only call this when this IO is a TTY, such as a not redirected stdin.
    • テスト結果 crystal 0.22.0 on wandbox
begin
  array = STDIN.raw.each_line.map{|line| line.dup}
  puts array.class

  array.each_with_index{|line, index| puts "#{line} <- #{index}"}
  #p array.size
rescue ex
  puts ex.message
end
  • 出力
Start
Using compiled compiler at .build/crystal
can't set IO#raw: Inappropriate ioctl for device
0
Finish

STDIN 直で

begin
  array = STDIN.each_line.map{|line| line.dup}
  puts array.class

  array.each_with_index{|line, index| puts "#{line} <- #{index}"}
  #p array.size
rescue ex
  puts ex.message
end
  • 出力
Start
Using compiled compiler at .build/crystal
Iterator::Map(IO::LineIterator(IO::FileDescriptor, Tuple(), NamedTuple()), String, String)
aaa <- 0
hello <- 1
world <- 2
0
Finish

もう少し短く

  • crystalのmapの省略記法は:ではなく.
array = STDIN.each_line.map(&.to_s)
  • 自動で配列になってくれないので、to_a をつける
array = STDIN.each_line.map(&.to_s).to_a
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