danielewski.dev

Custom Error on Missing Hash Key

product = {
  id: 123,
  infos: {
    name: 'Yellow Table',
    price: 15_000
  }
}

product.fetch(:infos).fetch(:image)
# => KeyError (key not found: :image)


product.fetch(:infos).fetch(:image) do |key|
  raise "Invalid product (missing #{key})"
end
# => RuntimeError (Invalid product (missing image))