【0は真】Rubyの条件式【オブジェクト可】

一般に、条件式の書き方は2通りあります。
(条件式とは、if (この部分!)then です)

  • 比較演算子や論理演算子を使う(true か false)
  • 変数や定数を単項で使う(値)


Rubyでは、Boolean型に加え、どんな値でも条件式にできます。
(言語によっては、Boolean型限定や数値のみといった制約がある)


で、falseとnil以外はtrueと判定されます。
(0や空文字("")もtrueです)


つまり、変数を条件式につっこんでやれば、それだけでNULLチェックができるとことです。


例として、前回の改造バージョンを。

require 'fileutils'
include FileUtils

def collect_file(collect_file,
                 output_dir,
                 current_dir = nil)

  collect_extention = File.extname(collect_file)

  cd(current_dir) if current_dir

  begin
    mkdir(output_dir)
  rescue Errno::EEXIST
    print "overwrite?(y/n)>"
    exit if /^y/i !~ gets
  end

  Dir.glob("*/#{collect_file}") do |file_path|
    dir_name = file_path.split("/")[-2]
    begin
      cp(file_path,
         "#{output_dir}/#{dir_name}.#{collect_extension}",
         {:preserve => true})
    rescue
      puts "#{file_path} couldn't copy."
    end
  end
end

ここでおさらいなど。

  • 引数のcurrent_dir = nil … 3つめの引数が省略された場合、仮引数にデフォルト値(今回はnil)を設定します。
  • cd(current_dir) if current_dir … (処理) if (条件式)というif文の書き方で、(条件式)がtrueの場合のみ(処理)を実行します。


で、本題はこちら。

  cd(current_dir) if current_dir

条件式に変数を指定しています。中身がnilなら処理は行われず、もしオブジェクトなら実行されます。数値以外でも問題無しです。


このように、nil(NULL)かどうかの判定に余計な演算子は必要ありません。Rubyの条件式の判定方法は、それが、あるか、ないか。という、とてもシンプルなものなのです。


be simple!