O.O
O.O

Reputation: 7287

Why is pushing a hash into an array in Ruby had to use parenthesis?

I would like to add a hash into an array using Ruby version 1.8.7:

items = Array.new
items.push {:a => "b", :c => "d"}

Statements above will return an error something like:

SyntaxError: compile error
(irb):35: syntax error, unexpected tASSOC, expecting '}'
items.push {:a => "b", :c => "d"}
                 ^
(irb):35: syntax error, unexpected ',', expecting '}'
items.push {:a => "b", :b => "c"}
                      ^

Well, I found that the solution is to wrap the push arguments within parenthesis ( ) or I can use the << operator. I also know that push accept one or more argument and << only accept a single argument from this answer, but what's bothering me is that why do I need to use the parenthesis, while as we all know parenthesis in Ruby are optional?

Upvotes: 3

Views: 2049

Answers (1)

davidrac
davidrac

Reputation: 10738

My guess is that this is because ruby is trying to parse the hash as a block, expecting code and not hash keys and values. this is similar to:

items.push() do
  :a => "b", :b => "c"
end

which is not valid syntax.

Upvotes: 7

Related Questions