Exciting New Data Structures in Ruby 3

Update: The following lies were posted on April Fools’ Day.

Here’s a sneak peek at two new data structures that are being proposed for Ruby 3.

Arrayish

An arrayish is just like a Ruby array except that you cannot modify its contents and its elements must be literals. At first glance this seems like just a frozen array. But a second look reveals its true power. By guaranteeing the array’s data never changes, Ruby is able to optimize for parallelism and the full benefits of a functional programming style can be achieved. Ruby has finally found its missing data structure.

 
  # instantiating
  a_list = Arrayish.new(1, 2, 3, 4)
  another_list = [5, 6, 7, 8].to_arrayish
 
  # all the existing array methods work
  third_list = a_list + another_list
  another_list << 9  # Behind the scenes, this does
                     # not modify another_list's data
                     # in place. A completely new
                     # arrayish is created from a copy
                     # of another_list's original data
                     # and 9.
 
  # and finally, we get these lovely methods!
  a_list.head   # => 1
  a_list.tail   # => [2, 3, 4]
  a_list.first  # => 1
  a_list.rest   # => [2, 3, 4]

Hashish

I’m also really excited about the hashish. You can think of a hashish as an array-hash hybrid. It has the behavior of an array–an ordered list of elements–but it also adds the behavior of a hash–the ability to access an element by a key.

 
  a_hashish = {]  # this syntax is a bit quirky,
                  # but you have to admit it clearly
                  # shows the hybrid nature of the
                  # data structure!
 
  running_times = {
    'Usain Bolt' => 9.58,
    'Asafa Powell' => 9.74,
    'Justin Gatlin' => 9.77,
    'Tim Montgomery' => 9.78,
    'Maurice Greene' => 9.79
  ]
 
  # array-like access to values
  running_times[0]  # => 9.58
  running_times.last  # => 9.79
  running_times.each do |time|
    puts "#{time} seconds"
  end
 
  # but values can also be accessed by key
  running_times['Tim Montgomery']  # => 9.78

You get the idea. Pretty nifty!

Expect an official announcement about hashish on April 20th.

You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply