Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Data.define

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 homogenous 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 · 4.0 · 3.4 · 3.2