Hellboy
Hellboy

Reputation: 1239

Syntax error possibly due to different ruby versions

I have this line of code in my function:

people << {"id": person.id, "name": person.name, "age": person.age}

This ran fine in my development environment. But in my friend's pc, it says there is a syntax error in this line. It says that the colon in "id": person.id is wrong. Writing the above code as "id"=> person.id fixed the issue. Is this issue possibly due to different ruby versions?

Upvotes: 0

Views: 73

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369420

people << {"id": person.id, "name": person.name, "age": person.age}

This syntax is new in 2.2.0. Before 2.2, the Symbols in the JSON-style Hash literals could only be valid Ruby identifiers (strictly speaking, valid Ruby labels) and could not be quoted.

See Feature #4276: Allow use of quotes in symbol syntactic sugar for hashes for details.

Writing the above code as "id"=> person.id fixed the issue.

Those two are not equivalent! The Hash above has Symbols as keys, your replacement has Strings as keys. There are several equivalent notations for the Hash literal above, but yours isn't:

{ id: person.id, name: person.name, age: person.age }                # 1.9+
{ 'id': person.id, 'name': person.name, 'age': person.age }          # 2.2+
{ :id => person.id, :name => person.name, :age => person.age }       # all versions
{ :'id' => person.id, :'name' => person.name, :'age' => person.age } # all versions
{ :"id" => person.id, :"name" => person.name, :"age" => person.age } # all versions

I ordered them roughly in order of preference, with the first one being the most preferred. You shouldn't quote Symbol literals that don't need quoting, and you shouldn't use double quotes if you don't intend to use interpolation.

Upvotes: 2

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

Your friend is probably using Ruby < v1.9.

That short syntax was introduced in 1.9. Before that it was all hash rocket (=>) syntax.

Upvotes: -1

Related Questions