Tag: Ruby 3.1

Ruby 3.1 Hash Value Omission

Ruby 3.1 introduces a neat feature (Feature #14579):

Values in Hash literals and keyword arguments can be omitted.

{x:, y:} is syntactic sugar for {x: x, y: y}.

foo(x:, y:) is syntactic sugar for foo(x: x, y: y).

For a real world example, this code:

ActionCable.server.broadcast 'matestack_ui_core',
{ event: 'route_status_update',
  very_late_count: very_late_count,
  late_count: late_count,
  nominal_count: nominal_count,
  early_count: early_count,
  very_early_count: very_early_count
}

becomes:

ActionCable.server.broadcast 'matestack_ui_core',
{ event: 'route_status_update',
  very_late_count:,
  late_count:,
  nominal_count:,
  early_count:,
  very_early_count:
}