LoginSignup
85
76

More than 5 years have passed since last update.

定番!Rubyでワンライナー書く時の基本テク

Last updated at Posted at 2013-12-14

ruby -e scriptを使うことで、ワンライナーを書くことができます。

アドホックな調べ物やフィルタ用途に便利なので日頃からよく使っています。
ただ、そのわりに案外書き方をド忘れてしがちなので、改めてまとめておきたくなりました。

標準出力に吐き出す

お馴染み、Kernel.#puts を使います。

エラー出力に吐き出す

Kernel.#warn を使います。

requireほげほげって書くの面倒臭い

-rオプションを使います。複数指定できます。

例えば、jsonとopen-uriをrequireして使う場合。

ruby -rjson -ropen-uri -e 'puts open("http://example.com").read.to_json'

引数を取る

Object::ARGVを使います

標準入力から読み込んで1行ずつ順繰りに処理する

例えば、標準入力から読み込んで1行ずつ順繰りにputsする場合

STDIN.each {|line| puts line }

Object::STDIN定数については http://docs.ruby-lang.org/ja/2.0.0/method/Object/c/STDIN.html を参照してください。

どうしても複数行書きたい。ワンライナーとは何だったのか。

;で区切る

puts 'hoge'; puts 'huga'; puts 'piyo'
85
76
4

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
85
76