Share
Embed
従業員データ基盤でのパターンマッチをご紹介_Roppongi.rb スポンサーLT
ItoJum
September 10, 2026
Transcript
24 slides
-
パターンマッチとは • Ruby 3.0から使える • オブジェクトの構造をパターンで照合 • マッチした値をローカル変数に束縛できる crew =
{ name: "Bob", skills: [ { label: "PicoRuby", level: 3 } ] } case crew in { name: name, skills: [*, { label: "PicoRuby", level: level }, *] } "#{name}: PicoRuby レベル#{level} else "PicoRubyのスキルを持っていません" end パターンマッチの例 3 -
パターン⼀覧 Rubyのパターンマッチは以下のパターンが使える。 Valueパターン in 0 | in Integer | in
1..9 === で比較。クラス・範囲・正規表現もここ Variableパターン in x / in ^x 値を束縛する。^ を付けると既存の変数の値と比較 Hashパターン in { name: String => n } #deconstruct_keys を呼ぶ。ハッシュにマッチするか Arrayパターン in [Integer, *rest] #deconstruct を呼ぶ。配列の要素にマッチするか Findパターン in [*, nil, *] 配列の中から条件に合う要素を探す Alternativeパターン in :a | :b | :c いずれかにマッチするか 4 -
List内部のオブジェクトのNotNull判定 def is_element_non_null?(obj_type) case obj_type when ::GraphQL::Schema::NonNull inner_type = obj_type.of_type
if inner_type.is_a?(::GraphQL::Schema::List) is_inner_type_non_null?(inner_type) end when ::GraphQL::Schema::List is_inner_type_non_null?(obj_type) else false end end def is_inner_type_non_null?(obj_type) inner_type = obj_type.of_type inner_type.is_a?(::GraphQL::Schema::NonNull) end パターンマッチ不使⽤ 8 -
List内部のオブジェクトのNotNull判定 def is_element_non_null?(obj_type) case obj_type when ::GraphQL::Schema::NonNull inner_type = obj_type.of_type
if inner_type.is_a?(::GraphQL::Schema::List) is_inner_type_non_null?(inner_type) end when ::GraphQL::Schema::List is_inner_type_non_null?(obj_type) else false end end def element_non_null?(obj_type) case obj_type in { of_type: { of_type: ::GraphQL::Schema::NonNull} } | { of_type: ::GraphQL::Schema::NonNull} true else false end end def is_inner_type_non_null?(obj_type) inner_type = obj_type.of_type inner_type.is_a?(::GraphQL::Schema::NonNull) end パターンマッチ不使⽤ パターンマッチ使⽤!! 9 -
List内部のオブジェクトのNotNull判定 def is_element_non_null?(obj_type) case obj_type when ::GraphQL::Schema::NonNull inner_type = obj_type.of_type
if inner_type.is_a?(::GraphQL::Schema::List) is_inner_type_non_null?(inner_type) end when ::GraphQL::Schema::List is_inner_type_non_null?(obj_type) else false end end スッキリ!!! def element_non_null?(obj_type) case obj_type in { of_type: { of_type: ::GraphQL::Schema::NonNull} } | { of_type: ::GraphQL::Schema::NonNull} true else false end end def is_inner_type_non_null?(obj_type) inner_type = obj_type.of_type inner_type.is_a?(::GraphQL::Schema::NonNull) end パターンマッチ不使⽤ パターンマッチ使⽤!! 10 -
パターン⼀覧 GraphQL RubyのNotNullとListに Rubyのパターンマッチは以下のパターンが使える。 このメソッドがない... Valueパターン in 0 | in
Integer | in 1..9 === で比較。クラス・範囲・正規表現もここ Variableパターン in x / in ^x 値を束縛する。^ を付けると既存の変数の値と比較 Hashパターン in { name: String => n } #deconstruct_keys を呼ぶ。ハッシュにマッチするか Arrayパターン in [Integer, *rest] #deconstruct を呼ぶ。配列の要素にマッチするか Findパターン in [*, nil, *] 配列の中から条件に合う要素を探す Alternativeパターン in :a | :b | :c いずれかにマッチするか 12