📝

[Feature #21545] TypeError が発生しない #dig メソッドを追加する提案

に公開

[Feature #21545] #try_dig, a dig that returns early if it cannot dig deeper

  • #dig は参照するオブジェクトに #dig メソッドがないと次のように TypeError が発生する
{ a: "foo" }.dig(:a, :b)
# => error: String does not have #dig method (TypeError)
  • こういう場合に TypeError にせず nil を返すようにする #try_dig を追加するチケット
{ a: "foo" }.try_dig(:a, :b)
# => nil
  • 具体的な利用ケースとしては以下のように API のレスポンスのデータ構造に依存せずに #dig をする、みたいな例が提示されている
api_response = { status: "ok" }
api_response.try_dig(:status, :code) # => nil

api_response = { status: { code: 200 } }
api_response.try_dig(:status, :code) # => 200
def match(input)
  case input
  in { status: { code: Integer => status } }
    puts "Status code: #{status}"
  in { status: status }
    puts "Other status: #{status}"
  else
    raise "mismatch: #{input}"
  end
end

match({ status: "ok" })
match({ status: { code: 200 } })
  • あんまりこの手のメソッドがほしいと思ったことはなかったけどどうだったかなあ
GitHubで編集を提案

Discussion