LoginSignup
1

More than 1 year has passed since last update.

ターミナルからRubyでも(標準入出力)

Last updated at Posted at 2020-12-29

!macOS-11.1 !ruby-2.7.2p137

Preface (はじめに)

本記事はマルチスケールシミュレーション特論の第5回に関連する記事です. チャート式Rubyに従って進めていきます.

今回はチャート式ruby-I(puts)に従ってRubyの標準入出力を学んでいきます.

Ruby

標準入出力

まずはお馴染み

hello world.

この文字列を返すプログラムを作ります.

  1. 文字列の出力

    Rubyで文字列を出力するための関数は複数あります.

    代表的なものは

    method 説明 改行
    print 引数のオブジェクトを文字列にし標準出力する. ×
    puts 引数のオブジェクトを文字列にし改行を加えて標準出力する.
    p debug用のputs, エスケープ処理された文字列でも処理されずに生の文字列が標準出力される.
    pp pのpretty print, pよりも分かりやすく標準出力する. require'pp'が必要.

    では, 早速作っていきましょう.

    hello_world.rb
    print "hello world1"
    puts "hello world2"
    p "hello world3"
    pp "hello world4"
    

    出力は

    > ruby hello_world.rb
    
    hello world1hello world2
    "hello world3"
    "hello world4" 
    
  2. 文字列の入力

    出力の次は入力でしょ!

    ということで, 次にgetsメソッドを用いて好きな文字列に挨拶します.

    hello_name.rb
    name = gets
    puts "hello " + name
    

    出力は

    > ruby hello_name.rb
    
    W
    hello W
    

    今度はCLIで作業をしたいので, ARGV[0]を使いたいと思います.

    hello_name.rb
    puts "hello #{ARGV[0]}"
    

    出力は

    > ruby hello_name.rb W
    -> hello W
    

類題

リダイレクト>を使って標準出力を適当なファイルに書き込んでみます.

> ruby hello_name.rb Woo > hello_name.txt

ちゃんと出力されたか確認

> cat hello_name.txt
-> hello Woo

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
What you can do with signing up
1