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.
- Ruby学习笔记(20)_符号Symbol
- Ruby 学习笔记 Symbol
- Ruby的符号(Symbol)
- 理解 Ruby Symbol (Ruby中的符号)
- Ruby学习笔记_单元测试
- [Ruby笔记]30.Ruby hash symbol 在哈希表中用符号作为键
- ruby入门_符号
- ruby学习笔记(11)--symbol与hash参数
- Ruby学习笔记_对象过程
- Ruby学习笔记_异常处理rescue
- Ruby学习笔记(03)_变量
- Ruby学习笔记(04)_判断
- Ruby学习笔记(05)_循环
- Ruby学习笔记(07)_块
- Ruby学习笔记(08)_模块Module
- Ruby学习笔记(09)_数组
- Ruby学习笔记(12)_范围Range
- Ruby学习笔记(13)_迭代器
- 笔记12
- 每秒处理10万订单支付架构
- JAVA多线程实现的三种方式
- Activity跳转动画,无缝链接
- 安装程序无法继续。Microsoft Runtime DLL安装程序未能完成安装
- Ruby学习笔记(20)_符号Symbol
- ASP访问Excel数据,忽然不能正常访问
- Java多线程学习(吐血超详细总结)
- Unit13
- Linux安装RocketMQ
- 调整数组顺序使奇数位于偶数前面
- FFmpeg发送流媒体的命令(UDP,RTP,RTMP)
- wifi p2p direct和wifi display两者发出request帧的差异
- Doolittle分解法(LU分解)详细分析以及matlab的实现