From: Peter Hickman Date: 2010-07-07T19:54:49+09:00 Subject: Re: Hashes don't allow preceding commas by design? --001485f1e7a66db814048ac9ffab Content-Type: text/plain; charset=ISO-8859-1 On 7 July 2010 11:02, Josh Cheek wrote: > > So line 4 is taken to be a continuation of lines 1, 2 and 3 and finally > > completes the statement that started on line 1. > > > > Your explanation implies to me that the OP's desired use case is valid. If > "line 4 is taken to be a continuation of lines 1, 2 and 3" then how come > line 4 can't be ",:jim => 43" > I can understand the confusion but it can be explained like this "A hash is a '{' followed by a comma separated list of key / value pairs finished off with a '}'" So if we read through a couple of examples: 1: { 2: :first => 1, 3: :second => 2 4 } Line 1 starts the hash declaration, the parser is looking for a key value pair or a '}' Line 2 is a key value pair and a comma. The comma tells the parser than it should expect another key value pair Line 3 is the next key value pair and does not have a comma. So the parser has come to the end of the list of key value pairs that makes up a hash and is therefore expecting a '}' Line 4 is the expected '}' and the hash declaration is complete Now try this: 1: { 2: :first => 1 3: :second => 2 4 } Again line 1 starts the hash declaration, the parser is looking for a key value pair or a '}' Line 2 is a key value pair and does not have a comma. So the parser believes that it has come to the end of the list of key value pairs and is therefore expecting a '}' Line 3 is a key value pair but the parser is expecting a '}' so this is an error. The compiler spits out the error. We never get to line 4. This goes back to what I said about 'incomplete' lines ":first => 1," is incomplete because the comma makes the parser think that another key value pair should be expected because it is parsing a hash declaration. So line 3 is treated as a continuation of line 2 and all is well with the world. However ":first => 1" is a complete line, the absence of a comma does not set the parser up to expect another key value pair. So when it encounters ":second => 2" it goes "what is going on here, according to my rules the next thing I should find is an '}'". It is not to say that the parser couldn't handle this situation or at least handle a line like ", :second => 2" (with a leading comma) but it does not as currently implemented. Some languages use things like a ';' as an explicit end of statement marker to help the parser. Ruby does not do this and treats the end of a line to be the implicit end of statement marker unless the statement appears to be incomplete. What constitutes incomplete depends on what it is parsing, a hash, a list, an if statement etc. --001485f1e7a66db814048ac9ffab--