3

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?

Community
  • 1
  • 1
O.O
  • 7,179
  • 1
  • 34
  • 32

1 Answers1

7

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.

davidrac
  • 10,723
  • 3
  • 39
  • 71
  • oddly, `items.push :a => "b", :c => "d"` works just as expected… – Patrick Oscity Jul 03 '12 at 09:41
  • 1
    @padde That's because the curly brackets `{}` are missing, so ruby does not make the mistake of parsing it as a block. Instead it gets parsed correctly as a method call `push(:a => "b", :c => "d")`. The original problem is created because you have an ambiguous situation where the ruby compiler will need to "guess" what you are meaning (block or method arguments). Because computers are not very good at reading your mind, it throws an error instead. – Casper Jul 03 '12 at 10:06