class RuboCop::Cop::Style::HashSyntax

Checks hash literal syntax.

It can enforce either the use of the class hash rocket syntax or the use of the newer Ruby 1.9 syntax (when applicable).

A separate offense is registered for each problematic pair.

The supported styles are:

all symbols for keys

syntax hashes

This cop has ‘EnforcedShorthandSyntax` option. It can enforce either the use of the explicit hash value syntax or the use of Ruby 3.1’s hash value shorthand syntax.

The supported styles are:

@example EnforcedStyle: ruby19 (default)

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

# good
{a: 2, b: 1}
{:c => 2, 'd' => 2} # acceptable since 'd' isn't a symbol
{d: 1, 'e' => 2} # technically not forbidden

@example EnforcedStyle: hash_rockets

# bad
{a: 1, b: 2}
{c: 1, 'd' => 5}

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

@example EnforcedStyle: no_mixed_keys

# bad
{:a => 1, b: 2}
{c: 1, 'd' => 2}

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

@example EnforcedStyle: ruby19_no_mixed_keys

# bad
{:a => 1, :b => 2}
{c: 2, 'd' => 3} # should just use hash rockets

# good
{a: 1, b: 2}
{:c => 3, 'd' => 4}

@example EnforcedShorthandSyntax: always

# bad
{foo: foo, bar: bar}

# good
{foo:, bar:}

# good - allowed to mix syntaxes
{foo:, bar: baz}

@example EnforcedShorthandSyntax: never

# bad
{foo:, bar:}

# good
{foo: foo, bar: bar}

@example EnforcedShorthandSyntax: either (default)

# good
{foo: foo, bar: bar}

# good
{foo: foo, bar:}

# good
{foo:, bar:}

@example EnforcedShorthandSyntax: consistent

# bad - `foo` and `bar` values can be omitted
{foo: foo, bar: bar}

# bad - `bar` value can be omitted
{foo:, bar: bar}

# bad - mixed syntaxes
{foo:, bar: baz}

# good
{foo:, bar:}

# good - can't omit `baz`
{foo: foo, bar: baz}

@example EnforcedShorthandSyntax: either_consistent

# good - `foo` and `bar` values can be omitted, but they are consistent, so it's accepted
{foo: foo, bar: bar}

# bad - `bar` value can be omitted
{foo:, bar: bar}

# bad - mixed syntaxes
{foo:, bar: baz}

# good
{foo:, bar:}

# good - can't omit `baz`
{foo: foo, bar: baz}