Skip to content
class method

Data.define

[KLASS < ::Data::_DataClass] (*::Symbol) ?{ (KLASS) [self: KLASS] -> void } -> KLASS
define(*symbols) → class

Defines a new Data class.

Example
measure = Data.define(:amount, :unit)
#=> #<Class:0x00007f70c6868498>
measure.new(1, 'km')
#=> #<data amount=1, unit="km">

# It you store the new class in the constant, it will
# affect #inspect and will be more natural to use:
Measure = Data.define(:amount, :unit)
#=> Measure
Measure.new(1, 'km')
#=> #<data Measure amount=1, unit="km">

Note that member-less Data is acceptable and might be a useful technique for defining several homogeneous data classes, like

Example
class HTTPFetcher
  Response = Data.define(:body)
  NotFound = Data.define
  # ... implementation
end

Now, different kinds of responses from HTTPFetcher would have consistent representation:

Example
#<data HTTPFetcher::Response body="<html...">
#<data HTTPFetcher::NotFound>

And are convenient to use in pattern matching:

Example
case fetcher.get(url)
in HTTPFetcher::Response(body)
  # process body variable
in HTTPFetcher::NotFound
  # handle not found case
end
See also .members .new also in 4.1 · 3.4 · 3.3 · 3.2