Ruby Symbols

In my learn Ruby in 48 hours project, I left one black box unopened, Now I am attacking it with a hammer and chisel. It’s those tiny little ‘:’ symbols scattered all over ruby code that’s bugging me. You find them in many different tutorials and books with little or no explaination.

Sample codes that contain ‘:‘ are a plenty in The Humble Little Ruby Book, but it doesn’t explain what these are. Someone had even popped a question about it at Stackoverflow, and coincidentally he has cited the same example I used in an earlier post.

So what the hell are those things anyway? They are symbols (couldn’t they have at least come up with a more imaginative name?). Ok so WTH is a symbol? according to RandomHacks they are memory leaks but that writer gives 12 other explanations as well. says “It’s a string. No it’s an object. No it’s a name.”

Perhaps things would become clearer if we figured out what’s the equivalent in PHP, but there isn’t an equivalent! How about Python? There isn’t one either. Thankfully a good enough explanation can be found on a SitePoint Ruby on Rails Tutorial: “In Ruby, a Symbol is a simple textual identifier. Like a String, a Symbol is created using literals; the difference is that a Symbol is prefixed with a colon :

car_colors =
  :kitt => 'black',
  :herbie => 'white',
  :larry => 'green',
  :batmobile => 'black'

Going by the sitepoint article, these are really suited for use as keys in hashes. ¬†According to the manual, symbols can also be generated by calling the to_sym method and a call to¬†Symbol.all_symbols will return an array of all the symbols that have been defined. Watch out, it’s going to be a pretty large array. And as a parting shot; please note that :'symbols can be pretty complicated, like this one'

May 14th, 2012 | Posted in Uncategorized
No comments yet.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>