gpt4 book ai didi

ruby-on-rails - Rails params "method"不是一种方法,是吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:20 24 4
gpt4 key购买 nike

Rails documentation , 下面的示例是作为显示服务器从 POST 请求接收到的内容的一种方式:

def create
render plain: params[:article].inspect
end

在随后的描述中,文字说明

The params method is the object which represents the parameters (or fields) coming in from the form. The params method returns an ActiveSupport::HashWithIndifferentAccess object.

虽然我知道所有方法都是对象,但我不明白将 params 对象称为方法是正确的。具体来说,短语“返回一个 ActiveSupport::HashWithIndifferentAccess 对象”向我暗示正在进行两个调用——在 Python 中可能看起来像:

params().__getitem__('article')

但我认为实际情况并非如此。

conversation围绕这些行也将 params 称为一种方法,所以我开始认为我一定遗漏了一些东西。

最佳答案

I'm new to Ruby, and while I understand that all methods are objects,

不,他们不是。方法属于对象(更准确地说:方法在模块中定义,并在对象的上下文中执行),但它们本身并不是对象。 (但是,可以通过调用返回 Method 对象的 method 方法来获得表示方法概念的反射代理。)

I don't understand how it's correct to refer to the params object as a method.

因为它是一种方法。不是对象。

还会是什么?从句法上看,很明显它只能是以下三种情况之一:关键字、变量或方法调用。

它不能是关键字,因为 Rails 只是一个 Ruby 库,而 Ruby 库不能更改语言的语法(例如添加或删除关键字)。它不能是变量,因为为了将其解析为变量,解析器需要在同一 block 中看到对它的赋值。

因此,它唯一可以可能的是方法调用。您甚至不需要对 Rails 有任何了解就可以知道这一点。这只是基本的 Ruby 语法 101。

Specifically, the phrase "returns an ActiveSupport::HashWithIndifferentAccess object" suggests to me that there are two calls going on--what in python might look like:

params().__getitem__('article')

but I don't think that's what's actually going on.

这正是正在发生的事情。您调用方法 params,然后对通过调用方法 params 返回的对象调用方法 []

这与 foo.bar 没有任何不同:您调用 foo,然后在 的返回值上调用 bar foo.

关于ruby-on-rails - Rails params "method"不是一种方法,是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28401534/

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