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

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
#=>:foo
sym.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 :steve
puts :steve.to_s
puts :steve.to_i
puts :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:

steve
steve
10257
Symbol
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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值