gpt4 book ai didi

ruby-on-rails - 为什么在 Ruby 中有时需要括号?

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:55 24 4
gpt4 key购买 nike

我最近在查看来自 Rails docs 的一些 Ruby 代码时遇到了一个奇怪的问题.

Ruby 允许您像下面的例子一样传递参数:

redirect_to post_url(@post), alert: "Watch it, mister!"
redirect_to({ action: 'atom' }, alert: "Something serious happened")

但我觉得第二种情况很奇怪。看起来你应该能够像这样传递它:

redirect_to { action: 'atom' }, alert: "Something serious happened"

不管有没有括号,它的意思都是一样的。但是你得到的是:

syntax error, unexpected ':', expecting '}'

指的是action之后的冒号。我不确定为什么它会在那里期待 },以及为什么使用括号会改变它。

最佳答案

因为 { ... } 有两个含义:哈希字面量和 block 。

考虑一下:

%w(foo bar baz).select { |x| x[0] == "b" }
# => ["bar", "baz"]

这里,{ ... } 是一个 block 。

现在假设您正在调用当前对象的方法,因此不需要显式接收器:

select { |x| x[0]] == "b" }

现在假设您不关心参数:

select { true }

这里,{ true } 仍然是一个 block ,而不是哈希。所以它在你的函数调用中:

redirect_to { action: 'atom' }

(大部分)等同于

redirect_to do
action: 'atom'
end

这是胡说八道。然而,

redirect_to({ action: atom' })

有一个参数列表,由哈希组成。

关于ruby-on-rails - 为什么在 Ruby 中有时需要括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com