south37の日記

ちょろっとメモりたい事とかを書く用。もうちょっとちゃんとしたブログもあります。http://south37.hatenablog.com/

rubyのcase

この記事でも言われてるみたいにクールな訳ですが。

クラスの判定も出来るんですね。

def pattern_match(val)
  case val
  when String  then p 'This is String!'
  when Integer then p 'This is Integer!'
  else              p 'This is not String nor Integer!'
  end
end

pattern_match('1')  // This is String!
pattern_match(1)    // This is Integer!
pattern_match(true) // This is not String nor Integer!

casewhen===メソッドが呼ばれる為、要は[クラス名] === [オブジェクト]でオブジェクトのクラスの判定が出来るってだけですが、書き方がクールだなって思いました。

===Moduleで定義されてるっぽいですね。 http://docs.ruby-lang.org/ja/2.0.0/class/Module.html