Possible Duplicate:
Understanding Symbols In Ruby
What is the colon operator in Ruby?可能重复:了解Ruby中的符号Ruby中的冒号运算符是什么?
This is some code the Rails tutorial I'm reading gives me.
这是我正在阅读的Rails教程给出的一些代码。
class Post < ActiveRecord::Base
attr_accessible :content, :name, :title
validates :name, :presence => true
validates :title, :presence => true,
:length => { :minimum => 5 }
end
What do the :content, :name, and :title mean? I vaguely remember these from the ruby tutorial I was reading (hlrb), but I can't find them when I'm skimming through it. What do these words prefixed by a colon mean?
什么:content,:name和:title是什么意思?我依旧记得这些来自我正在阅读的红宝石教程(hlrb),但是当我浏览它时我找不到它们。这些单词以冒号为前缀是什么意思?
1 个解决方案
#1
8
The words your referring to are called symbols.
你所指的词叫做符号。
What are symbols you ask? They are more or less like strings, except they are immutable (can't be changed) and are singletons (are only ever created once in memory, no matter how many times you use them).
你问的符号是什么?它们或多或少像字符串,除了它们是不可变的(不能改变)并且是单例(只在内存中创建一次,无论你使用它们多少次)。
That means that they get used as keys everywhere, because they are more memory efficient.
这意味着它们在任何地方都被用作密钥,因为它们的内存效率更高。
So if you have two hashes, for instance, and have a key called key, using a string for the hash key:
因此,如果您有两个哈希值,并且有一个名为key的键,则使用字符串作为哈希键:
my_hash['key'] #in memory once
your_hash['key'] # in memory twice
If you use a symbol
如果您使用符号
my_hash[:key] # in memory once
your_hash[:key] # still in memory once!
You may also encounter symbols in this form:
您可能还会遇到以下形式的符号:
key: 'value'
This is the same as
这是一样的
:key => 'value'
#1
8
The words your referring to are called symbols.
你所指的词叫做符号。
What are symbols you ask? They are more or less like strings, except they are immutable (can't be changed) and are singletons (are only ever created once in memory, no matter how many times you use them).
你问的符号是什么?它们或多或少像字符串,除了它们是不可变的(不能改变)并且是单例(只在内存中创建一次,无论你使用它们多少次)。
That means that they get used as keys everywhere, because they are more memory efficient.
这意味着它们在任何地方都被用作密钥,因为它们的内存效率更高。
So if you have two hashes, for instance, and have a key called key, using a string for the hash key:
因此,如果您有两个哈希值,并且有一个名为key的键,则使用字符串作为哈希键:
my_hash['key'] #in memory once
your_hash['key'] # in memory twice
If you use a symbol
如果您使用符号
my_hash[:key] # in memory once
your_hash[:key] # still in memory once!
You may also encounter symbols in this form:
您可能还会遇到以下形式的符号:
key: 'value'
This is the same as
这是一样的
:key => 'value'