Project

General

Profile

Actions

Feature #17292

closed

Hash Shorthand / Punning

Added by baweaver (Brandon Weaver) over 3 years ago. Updated over 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:100635]

Description

Set Literal vs Javascript Object Punning

There was a proposal for a Set literal here: https://bugs.ruby-lang.org/issues/16989

set = { 1, 2, 3 }

...but it was brought up that this is similar to the Javascript Object punning, or Object shorthand syntax:

const a = 1, b = 2, c = 3;

const punnedObject = { a, b, c }
// => { a: 1, b: 2, c: 3 }

Proposition: I believe we should use brackets ({}) for a shorthand Hash syntax similar to Javascript.

Hash Punning

My first proposal in this feature request is Hash punning, or Hash shorthand:

a = 1
b = 2
c = 3

{ a:, b:, c: }
# => { a: 1, b: 2, c: 3 }

This syntax avoids the ambiguous syntax of empty block ({}) versus empty set ({}), and with the presence of Symbols it introduces a distinct syntax that would be easier to parse against.

One potential issue would be mixed syntax:

{ a:, b: 2 }
# => { a: 1, b: 2 }

Method Punning

This syntax can also be used for keyword argument and method call punning:

def method_name(a:, b:, c:)
  a + b + c
end

a = 1
b = 2
c = 3

method_name(a:, b:, c:)
# => 6

I believe this existing syntax for required keywords gives credence to the idea of introducing punning to Ruby, as it's very similar to existing syntax, and therefor feels "Ruby-like".

Pattern Matching

This syntax is also already present and used in pattern matching, making it already part of the language:

case { x: 1, y: 2 }
in { x:, y: }
  { x:, y: y + 1} # new
else
  # ...
end

I believe this further justifies the case for punning syntax.


Related issues 2 (0 open2 closed)

Related to Ruby master - Feature #18124: Hash shorthands (matching constructors functionality in JS)ClosedActions
Is duplicate of Ruby master - Feature #14579: Hash value omissionClosedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0