Recipe 1.7. Converting Between Strings and Symbols

本文详细解释了Ruby中符号(Symbol)与字符串(String)的区别。符号是名称和内部ID的组合,相同名称的符号始终指向同一对象,这在内存和效率上优于字符串。文章通过实例演示了如何将字符串转换为符号,以及在不同场景下选择使用符号或字符串的指导原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To turn a symbol into a string, use Symbol#to_s, or Symbol#id2name, for which to_s is an alias.

1 puts :a_symbol.to_s
2 puts :AnotherSymbol.id2name
3 puts :"Yet another symbol!".to_s

Output:a_symbol
    AnotherSymbol
    Yet another symbol!

 

You usually reference a symbol by just typing its name. If you're given a string in code and need to get the corresponding symbol, you can use String.intern:

1 puts :dude.object_id
2 symbol_name = "dude"
3 puts symbol_name.intern
4 puts symbol_name.intern.object_id

Output:99538
    dude
    99538

 

A Symbol is about the most basic Ruby object you can create. It's just a name and an internal ID. Symbols are useful becase a given symbol name refers to the same object throughout a Ruby program.

Symbols are often more efficient than strings. Two strings with the same contents are two different objects (one of the strings might be modified later on, and become different), but for any given name there is only one Symbol object. This can save both time and memory.

1 puts "string".object_id
2 puts "string".object_id
3 puts :symbol.object_id
4 puts :symbol.object_id

Output:21299510
    21299490
    99698
    99698

If the contents (the sequence of characters) of the object are important, use a string.

If the identity of the object is important, use a symbol.

 

转载于:https://www.cnblogs.com/zhtf2014/archive/2009/11/05/1597032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值