Bug #12758
closedError when passing Hash construction to function
Description
I apologize if this is a known issue but I couldn't find it in the search.
If you have a function that can take a Hash, it behaves correctly if you pass a variable that contains the Hash compared to when you pass in a Hash construction using braces {}.
Example
def foo(a)
puts a.class
puts a
end
foo [1,2]
Array
[1, 2]
a = { a:1 }
foo a
Hash
{:a=>1}
This breaks¶
foo { a:1 }
SyntaxError: (irb):23: syntax error, unexpected ':', expecting '}'
foo {a:1}
^
but this works
foo( {a:1} )
Hash
{:a=>1}
This is more of a bug related to consistent syntax of the language and it is something that is allowed in Groovy and Scala
Updated by wanabe (_ wanabe) over 7 years ago
This is in FAQ.
Please see http://ruby-doc.org/docs/ruby-doc-bundle/FAQ/FAQ.html#s6 : "6.7 Why can't I pass a hash literal to a method: p {}?"
And you can pass a hash to method without braces when it is last argument.
irb(main):001:0> p a: 1
{:a=>1}
=> {:a=>1}
irb(main):002:0> p 1 => 2
{1=>2}
=> {1=>2}
irb(main):003:0> p a: 1, 2
SyntaxError: (irb):3: syntax error, unexpected '\n', expecting =>
from /usr/local/bin/irb:11:in `<main>'
irb(main):004:0>
Updated by shyouhei (Shyouhei Urabe) over 7 years ago
- Status changed from Open to Rejected
Let me reject this (a FAQ).