Grokify
Grokify

Reputation: 16354

How to create Crystal language Hash where values can be any type?

I'm working on representing an API where a response contains a hash where the keys are of type String and the values can be of any type. Is there a way to represent this in Crystal?

I did not see a way to represent this looking through Crystal docs on types:

In OpenAPI Spec, this is described as a free-form object:

https://swagger.io/docs/specification/data-models/dictionaries/#free-form

Free-Form Objects

If the dictionary values can be of any type (aka free-form object), use additionalProperties: true:

type: object additionalProperties: true

This is equivalent to:

type: object additionalProperties: {}

In Go, this would be represented as map[string]any or map[string]interface{}.

Upvotes: 1

Views: 608

Answers (1)

Grokify
Grokify

Reputation: 16354

Given that everything is an object in Crystal, the following compiles for me:

Hash(String, Object)

Everything is an object

In Crystal everything is an object. The definition of an object boils down to these points:

  • It has a type
  • It can respond to some methods

This is everything you can know about an object: its type and whether it responds to some method.

An object's internal state, if any, can only be queried by invoking methods.

Ref: https://crystal-lang.org/reference/1.6/syntax_and_semantics/everything_is_an_object.html

Ref: https://crystal-lang.org/api/1.8.2/Object.html

Upvotes: 3

Related Questions