ruby notes

Small things I keep relearning about Ruby.

Pattern matching on hashes

An API I call returns one of three shapes depending on its mood. I used to untangle it with a stack of dig and if. With case/in it reads like a description of the data:

case JSON.parse(body, symbolize_names: true)
in {status: "ok", data: {items: [_, *] => items}}
  process(items)
in {status: "ok", data: {items: []}}
  log_empty
in {status: "error", error: {code: Integer => code}}
  retry_later(code)
end

Hash patterns only check the keys you list, so extra fields do not break the match. If nothing matches you get NoMatchingPatternError, which is exactly what I want for an unexpected response.