使用hash作为参数时,没有花括号会有区别吗?

iro*_*and 1 ruby hash literals

这两个表达似乎没有区别.

h = {a: 1, b: 2}
h.merge({c: 3, d: 4})
h.merge(c: 3, d: 4)
Run Code Online (Sandbox Code Playgroud)

如果我在Hash用作参数时省略花括号,是否存在问题?

spi*_*ann 7

不,两个版本之间没有区别.

此外,当哈希是方法的最后一个参数时,省略大括号是一种常见的Ruby/Rails习语.比较以下常见示例:

validates :foo, { presence: true }
validates :foo, presence: true

link_to "Foos", foo_path, { class: "foo" }
link_to "Foos", foo_path, class: "foo"
Run Code Online (Sandbox Code Playgroud)