Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | コマンド展開

概要

Rubyの処理中にOSのコマンドを実行する方法について

詳細

Rubyではコマンド展開という記法により、OSのコマンドを実行できます。
文法は二種類あり、

バッククォートでくくる方法

`任意のcommand`

%xと記号でくくる方法

%x{任意のcommand}

サンプルコード

# encoding: Windows-31J
require "pp"

p `echo test`
p $? # 終了ステータスの照会
p %x|echo test|
p $? # 終了ステータスの照会

出力

"test\n"
#<Process::Status: pid 6656 exit 0>
"test\n"
#<Process::Status: pid 3076 exit 0>