:this 在 Ruby on Rails 中是什么意思? [英] What does :this means in Ruby on Rails?
问题描述
我是 Ruby 和 Ruby on Rails 世界的新手.我已经阅读了一些指南,但我在使用以下语法时遇到了一些麻烦.我认为在 Ruby 中使用 :condition
语法来定义具有某种访问器的类属性,例如:
I'm new to the Ruby and Ruby on Rails world. I've read some guides, but i've some trouble with the following syntax.
I think that the usage of :condition
syntax is used in Ruby to define a class attribute with some kind of accessor, like:
class Sample
attr_accessor :condition
end
隐式声明了条件"属性的 getter 和 setter.当我查看一些 Rails 示例代码时,我发现以下示例我并不完全理解.
that implicitly declares the getter and setter for the "condition" property. While i was looking at some Rails sample code, i found the following examples that i don't fully understand.
例如:
@post = Post.find(params[:id])
为什么它使用这种语法访问 id
属性,而不是:
Why it's accessing the id
attribute with this syntax, instead of:
@post = Post.find(params[id])
或者,例如:
Or, for example:
@posts = Post.find(:all)
:all
是一个常量吗?如果不是,这段代码的真正含义是什么?如果是,为什么不使用以下内容:
Is :all
a constant here? If not, what does this code really means? If yes, why the following is not used:
@posts = Post.find(ALL)
谢谢
推荐答案
文本前的冒号表示 Ruby 中的符号.一个符号有点像一个常量,但它几乎就像一个符号接收一个唯一的值(你不关心)作为它的常量值.
A colon before text indicates a symbol in Ruby. A symbol is kind of like a constant, but it's almost as though a symbol receives a unique value (that you don't care about) as its constant value.
当用作哈希索引时,符号几乎(但不完全)与使用字符串相同.
When used as a hash index, symbols are almost (but not exactly) the same as using strings.
此外,您可以通过在符号上调用 to_s
从 :all
读取all".如果您有一个常量变量 ALL
,除了查找它的值之外,没有办法确定它的意思是所有".这也是为什么您可以使用符号作为元方法的参数,例如 attr_accessor
、attr_reader
等.
Also, you can read "all" from :all
by calling to_s
on the symbol. If you had a constant variable ALL
, there would be no way to determine that it meant "all" other than looking up its value. This is also why you can use symbols as arguments to meta-methods like attr_accessor
, attr_reader
, and the like.
您可能想要阅读 Ruby 符号.
这篇关于:this 在 Ruby on Rails 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!