Tuesday, October 11, 2011

Symbol in ruby

A symbol in Ruby refers to a variable by name rather than by reference. In many cases, it may not refer to an identifier at all but rather acts like a kind of immutable string. A symbol can be converted to a string with the to_s method.
Hearts   = :Hearts   # This is one way of assigning
Clubs = :Clubs # unique values to constants,
Diamonds = :Diamonds # somewhat like an enumeration
Spades = :Spades # in Pascal or C.

puts Hearts.to_s # Prints "Hearts"

Symbol class in Ruby contains one class method all_symbols and instance methods id2name, inspect, to_i, to_int, to_s and to_sym.


The "enumeration" trick we reference here probably made more sense in the earlier days of Ruby, when there was no Symbol class, and applying the colon to an identifier yielded a simple integer. If you do use this trick, don't rely on the actual symbol values being regular or predictable; just use them as constants whose value is irrelevant.

No comments:

Post a Comment