Ray's playground

 

Recipe 1.7. Converting Between Strings and Symbols

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.

  •  

    posted on 2009-11-05 22:57  Ray Z  阅读(183)  评论(0编辑  收藏  举报

    导航