DEV Community

Kelly Popko
Kelly Popko

Posted on • Edited on

Ruby Data Class: Syntax

This is part 1 in this series on Ruby's Data Class. Part 2 compares Data with Struct. Part 3 explores immutability workarounds with Data.

What is the Data class?

A Ruby class to allow the definition of simple classes for value-alike objects.

Data is intended to store immutable values*.
Once defined, its instance cannot
*A future post will explore the wiggle room here.

Once defined, the instance of Data class is

A Ruby class designed to create for objects with the intention of being immutable.

The Data class was introduced to Ruby in Ruby 3.2, to:

  • 'define simple classes for value-alike'
  • store immutable atomic values

When was Data brought into Ruby?

Ruby 3.2

Create the blueprint (instance of Data class)

We call Data.define and pass keyword arguments.

Book = Data.define(:title, :author, :year)
Enter fullscreen mode Exit fullscreen mode

We can define methods as well if we pass it a block.

Book = Data.define(:title, :author, :year) do
  SUMMARY = '%<title>s was written by %<author>s in %<year>i.'

  def to_s
    SUMMARY % {title:, author:, year:}
  end
end
Enter fullscreen mode Exit fullscreen mode
hobbit = Book.new("The Hobbit", "J.R.R. Tolkien", 1937)
puts hobbit
# => nil
'The Hobbit was written by J.R.R. Tolkien in 1937.'
Enter fullscreen mode Exit fullscreen mode

Building from the blueprint

  • Call .new or use [] notation
  • Use keyword or positional arguments

.new + keyword arguments

hobbit = Book.new(title: "The Hobbit", author: "J. R. R. Tolkien", year: 1937)
# => <data Book title="The Hobbit", author="J. R. R. Tolkien", year=1937>

hobbit.author
# => "J. R. R. Tolkien"

hobbit.year
# => 1937

hobbit.title
# => "The Hobbit"
Enter fullscreen mode Exit fullscreen mode

Bracket Notation + Positional arguments

Location = Data.define(:latitude, :longitude)
# => Location
Enter fullscreen mode Exit fullscreen mode

We can use positional arguments but need to take care with the order.

philadelphia = Location[39.9526, -75.1652]
# => #<data Location latitude=39.9526, longitude=-75.1652>

philadelphia.latitude
# => 39.9526

philadelphia = Location[-75.1652, 39.9526]
# => #<data Location latitude=-75.1652, longitude=39.9526>

philadelphia.latitude
# => -75.1652
Enter fullscreen mode Exit fullscreen mode

Bracket Notation + Keyword Arguments

Note that with keyword arguments, we have flexibility in the order we pass arguments.

philadelphia = Location[latitude: 39.9526, longitude:-75.1652]
# => #<data Location latitude=39.9526, longitude=-75.1652>

philadelphia.latitude
# => 39.9526
Enter fullscreen mode Exit fullscreen mode
philadelphia = Location[longitude:-75.1652, latitude: 39.9526]
# => #<data Location latitude=39.9526, longitude=-75.1652>

philadelphia.latitude
# => 39.9526
Enter fullscreen mode Exit fullscreen mode

Further Reading

Top comments (0)