max pleaner max pleaner - 16 days ago 4
Ruby Question

Aren't parenthesis supposed to be optional when a hash is the last argument?

I am sure that this is usually the case, but I'm not sure why it's not working here:

Here's the code

let(:stubbed_object_list) { [OpenStruct.new key: "foo"] }


And here's the error:

SyntaxError: ...filepath...: syntax error, unexpected tLABEL, expecting ']'


I can fix the code by instead using
OpenStruct.new(key: "foo")
but I don't see why this is necessary.

I'm thinking it has something to do with the array brackets, because this works fine:

let(:stubbed_object_list) { OpenStruct.new key: "foo" }

Answer

It becomes ambiguous if you add another key-value pair:

[OpenStruct.new key: "foo", other: "bar"]

other: "bar" could be another array element:

[OpenStruct.new(key: "foo"), other: "bar"]
#=> [#<OpenStruct key="foo">, {:other=>"bar"}]

or another argument:

[OpenStruct.new(key: "foo", other: "bar")]
#=> [#<OpenStruct key="foo", other="bar">]