Omission of Curly Braces for a Hash in an Array

Omission of curly braces for a hash in an array

This would seem to be a new feature of 1.9:

$ rvm use 1.8.7
$ irb
ruby-1.8.7-p352 :001 > x = [ 1,2,3,:a => 4, :b => 5 ]
SyntaxError: compile error
(irb):1: syntax error, unexpected tASSOC, expecting ']'
x = [ 1,2,3,:a => 4, :b => 5 ]
^
from (irb):1
ruby-1.8.7-p352 :002 > exit
$ rvm use 1.9.3
$ irb
ruby-1.9.3-p0 :001 > x = [ 1,2,3,:a => 4, :b => 5 ]
=> [1, 2, 3, {:a=>4, :b=>5}]
ruby-1.9.3-p0 :002 >

What is this in ruby? A hash without curly brackets?

Ruby allows hash braces to be omitted in a number of places. Most commonly this is seen in method calls:

foo(arg, key: value)
# equivalent to (in Ruby 2):
foo(arg, {key: value})

The snippet you posted shows an array of two elements with the second one being a hash:

[ model, anchor: model.dom_id ]
# equivalent to:
[ model, {anchor: model.dom_id} ]

How to eager load deeper twice

As the error suggests, it's just a syntax error. You've used {:favorite, :comments => :author} which is not a valid Hash.

Use an array as the value for :original to do what you want:

Post.includes(:user, :original => [:favorite, :comments => :author]).all

Your confusion might stem from the omission of some curly braces for Hashes which are not required in all cases. Re-writing the above with the curly braces explicitly added might make it more clear:

Post.includes(:user, {:original => [:favorite, {:comments => :author}]}).all


Related Topics



Leave a reply



Submit