辞書的定義 • データを検索する場合に、特 定のパターンが出現するかど うか、またどこに出現するか を特定する手法(Wikipedia) Dictionary definition Pattern matching is the act of checking a perceived sequence of tokens for the presence of the constituents of some pattern
分解 val re = """(¥d+)-(¥d+)-(¥d+)""".r // 正規表現オブジェクトの生成 "2012-09-15" match { case re(yyyy, mm, dd) => (yyyy, mm, dd) } // => ("2012", "09", "15") // Create a Regex object Deconstructuring
分解 • 分解するために必要なこと – Deconstructorのクラスに Deconstructableをincludeする – Deconstructorに deconstructメソッドを定義する with(Array.(a, b)) Deconstructor Deconstructuring What you need to deconstruct an object Include Deconstructable in a class of Deconstructor Define deconstruct method for Deconstructor
分解 class Regexp include PatternMatch::Deconstructable def deconstruct(val) m = Regexp.new("¥¥A#{source}¥¥z", options).match(val.to_s) raise PatternNotMatch unless m m.captures.empty? ? [m[0]] : m.captures end end Deconstructuring
利用例(テキスト処理) • パターンマッチなし ARGF.each do |i| cols = CSV.parse_line(i) if cols.length == 2 date = Date.parse(cols[0]) rescue nil m = cols[1].match(/(¥w+) (¥w+)/) if date and date.year == 2012 and (1..6).includes?(date.month) and m mm = date.month name, last = m.captures ... Examples(Text processing) Without pattern matching