Sangaku
Sangaku

Reputation: 95

Create a ruby hash with special characters in the key, new syntax

The new ruby syntax allows:

states = {
  Oregon: 'OR',
  Florida: 'FL',
  California: 'CA',
}

How could I add something like:

states = {
  New York: 'NY'
}

I get an error if I try New\ York: or 'New York':

Upvotes: 3

Views: 2646

Answers (3)

tadman
tadman

Reputation: 211540

You can define it in the inverse order, then applyinvert to flip it back:

states = {
  OR: :"Oregon",
  FL: :"Florida",
  CA: :"California",
  NY: :"New York"
}.invert

This has symbol keys and values, but you can always convert the values to strings as required.

The "new style" hash declarations are quite limited in the sort of keys you can define unless you use a more formal style like :"New York" => '...'.

Upvotes: 1

Taymon
Taymon

Reputation: 25656

This cannot be done in the new syntax.

Ruby's formal grammar unfortunately isn't documented anywhere, but the source code shows that the parser expects a tLABEL, which means that keys in the new syntax must follow the same rules as Ruby identifiers.

Upvotes: 3

sawa
sawa

Reputation: 168071

You cannot use that syntax. Do this:

states = {
  :"New York" => "NY"
}

or

states = {
  "New York".to_sym => "NY"
}

Upvotes: 9

Related Questions