Hash Syntax

Hi All,

is it possible to omit the commas when defining a Hash like this?

h = {
‘key1’ => ‘value1’, # comma
’key2’ => ‘value2’, # comma
’key3’ => ‘value3’ # no comma
}

The key/value pairs are devided by a linefeed. Can we teach ruby to
understand it also without the comma?
I want to generate Hash definitions dynamically by another program and
to omit the commas would be very useful.

thank you!

Dominik

The key/value pairs are devided by a linefeed. Can we teach ruby to
understand it also without the comma?

Well, if you want to write it

   h = {
      'key1' => 'value1' # no comma
      'key2' => 'value2' # no comma
      'key3' => 'value3' # no comma
   }

then no, ruby will give a parse error,

I want to generate Hash definitions dynamically by another program and
to omit the commas would be very useful.

  but you can write it

   h = {
      'key1' => 'value1', # comma
      'key2' => 'value2', # comma
      'key3' => 'value3', # comma
   }

Guy Decoux

ts wrote:

“D” == Dominik Werder dwerder@gmx.net writes:

The key/value pairs are devided by a linefeed. Can we teach ruby to
understand it also without the comma?

Well, if you want to write it

h = {
‘key1’ => ‘value1’ # no comma
‘key2’ => ‘value2’ # no comma
‘key3’ => ‘value3’ # no comma
}

then no, ruby will give a parse error,

I want to generate Hash definitions dynamically by another program and
to omit the commas would be very useful.

but you can write it

h = {
‘key1’ => ‘value1’, # comma
‘key2’ => ‘value2’, # comma
‘key3’ => ‘value3’, # comma
}

If your keys and values are always strings, you can do this:

h = Hash[*%w{
key1 value1
key2 value2
key3 value3
}]

Hi!

  'key1' => 'value1',    # comma
  'key2' => 'value2',    # comma
  'key3' => 'value3',    # comma

Yes, this works fine :slight_smile:

If your keys and values are always strings, you can do this:

h = Hash[*%w{
key1 value1
key2 value2
key3 value3
}]

They’re strings but with whitespace (sometimes)

Thank you!

Dominik