Ruby学习笔记(20)_符号Symbol

来源:互联网 发布:黑魂3捏脸 防火女 数据 编辑:程序博客网 时间:2024/05/29 14:31

Symbol的一篇文章结合ruby基础教程综合 博客原文

What do symbols look like?

This is the one area where everyone agrees. Most symbols looks like a colon followed by a non-quoted string:
:myname

符号能实现的功能,大部分字符串也能实现。但像散列键这样只是单纯判断“是否相等”的处理中,使用符号会比字符串比较更加有效率,因此在实际编程中我们也会时常用到符号。

另外,符号与字符串可以互相任意转换。对符号使用 to_s 方法,则可以得到对应的字符串。反之,对字符串使用 to_sym 方法,则可以得到对应的符号。

sym = :foo#=>:foosym.to_s#=> "foo"

Symbol是不变的

不可以像其他变量一样对它进行赋值运算。比如这样的写法是错误的:myname = “Tom”,这么写会报错。 相反Symbol可以作为值赋给其他变量比如mystring = :myname

What are symbols ?

It’s a string. No it’s an object. No it’s a name.

There are elements of truth in each of the preceding assertions, and yet in my opinion they are not valuable, partially because they depend on a deep knowledge of Ruby to understand their significance. I prefer to answer the question “what are symbols” in a language independent manner:

A Ruby symbol is a thing that has both a number (integer) representation and a string representation.

Let’s explore further using code:

puts :steveputs :steve.to_sputs :steve.to_iputs :steve.class

The preceding code prints four lines. The first line prints the string representation because that’s how the puts() method is set up. The second line is an explicit conversion to string. The third is an explicit conversion to integer. The fourth prints the type of the symbol. The preceding code results in the following output:

stevesteve10257Symbol
Based on what’s been presented in this section, we can add to the language independent answer to the question “what is a symbol”:

1.A Ruby symbol is a thing that has both a number (integer) representation and a string representation.

2.The string representation is much more important and used much more often.
3.The value of a Ruby symbol’s string part is the name of the symbol, minus the leading colon.
4.A Ruby symbol cannot be changed at runtime.
5.Multiple uses of the same symbol have the same object ID and are the same object.
原创粉丝点击