I keep seeing many programmers from different backgrounds are unable to get what Ruby symbols are, and though I do know that there are many great posts regarding this topic, and actually my intent is not to increase them by one
, but I feel I have to clear few points regarding them.
So I’m trying to answer 2 important question here: What are Ruby symbols? and When to use them?
What are Ruby symbols?
Well, according to the API documentation:
Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :”string” literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
Let’s walk over this long quote, point by point, but let’s first list all the points it has:
1-Symbol objects represent names and some strings inside the Ruby interpreter.
2-They are generated using the :name and :”string” literals syntax, and by the various to_sym methods.
3-The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
I’ll start with the 2nd point then get back to the rest, just before I do, please fire your irb:
We can create a symbol with various ways:
# Normal way, just prefix a token with ':' greeting = :hi #=> :hi # Multi token symbol another_greeting = :"hello man" #=> :"hello man" # Use the .to_sym if it's defined for your object class # For example .to_sym is defind in String class a_third_greeing = "howdy".to_sym #=> :howdy # Using %s[ ] %s[a 4th one] #=> :"a 4th one" # We can also cast a symbol to string with to_s :ds.to_s #=> "ds" |
That was the easy part, now let’s get back to the first point, it says: “Symbol objects represent names and some strings inside the Ruby interpreter.” , what does that mean exactly?
In computer science there is a term called: Symbol table, where the compiler or the interpreter of the language stores all the identifiers of a source code in that table to reference them -specifically to be referenced by the Abstract Syntax Tree(AST).
Actually the data structure that represents the symbol table varies from one interpreter to another, but what we care for is Ruby, in Ruby, the symbol table stores various things like method names and symbol names(we will check why Ruby does so later on), and the value of a symbol is a unique integer value, that can’t be changed.
# Not working on ruby 1.9 :ds.to_i #=> 28777 # Notice the value of the symbol is not its object id :ds.object_id #=> 287778 # Symbol values can't be changed :ds = 3 #SyntaxError: compile error |
Now let’s take more in depth example, let’s explore the symbol table:
# Let's check what symbols names start with 'hello' Symbol.all_symbols.collect{|x| x.to_s}.grep /^hello.*$/ #=> ["hello"] # Now let's define a new dummy class and add a new method called 'hello_world' class Dummy; def hello_world; end ; end #=> nil # Check again. Symbol.all_symbols.collect{|x| x.to_s}.grep /^hello.*$/ #=> ["hello", "hello_world"] |
As you can see, when we defined the class ‘Dummy’ and more specifically when we defined the ‘hello_world’ method, it was added to the symbol table.
Let’s take another example:
Symbol.all_symbols.size #=> 3329 :koko #=> :koko Symbol.all_symbols.size #=> 3330 |
Now let’s take the last point : “The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.” ,so: Fred is :Fred wherever you see it and no matter what the context it comes in:
k = :Fred #=> :Fred module M; Cons = :Fred; end #=> :Fred k.object_id #=> 287498 M::Cons.object_id #=> 287498 |
When to use Ruby symbols?
Well, this might be the one million dollars question, and that’s initially why i wrote this post for. You also might be wondering, why have Matz chosen to give us this low level introspection in the language by allowing me to work with the interpreter stuff?
The answer is divided in 2 parts:
1- Efficiency. 2- Metaprogramming(reflection).
Efficiency
We will talk about efficiency at first place,so let’s check this snippet of code:
# Some programmer would do this if name == "khaled alhabache" |
The snippet of code above is really costive, in terms of memory and efficiency:
1-Comparing 2 strings is costive, specially when the 2 strings are long.
2-Reserving “changeable” amount of memory, 16 bytes in our case to instantiate “Khaled alhabache”.
3-The GC would have to clean this “Khaled alhabache” later on.
What about doing :
# This is what i call it "a cleaner approach" if name.to_sym == :"khaled alhabache" |
Now what we did is:
1-Comparing 2 integers(the value of a symbol is integer) which is cheaper.
2-Reserving memory 4 bytes for :”Khaled alhabache” symbol, cause a symbol is an integer finally.
3-The GC would not have to clean this :”Khaled alhabache” symbol, cause symbols don’t get deleted till program exits.
So use symbols as much as you can, and avoid using stings as much as you can, but take extra care of defining thousands of symbols, cause as mentioned: symbols don’t get deleted till program exits, and thus they stick in memory.
Metaprogramming and symbols
Well working with metaprogramming in Ruby is really nice, you can do something like:
to = [:to_s , :to_f , :to_r] #=> [:to_s, :to_f, :to_r] # Notice the use of symbols with reflection -Ex with 'send' method to.each{|method| puts "#{method} => #{5.send method}"} # to_s => 5 # to_f => 5.0 # to_r => 5 |
Without symbols, you would never be able to use reflection techniques like ‘send’, otherwise how can you invoke methods dynamically?, also without symbols, you would never be able to use introspection techniques like ‘respond_to?’
5.respond_to? :slice #=> false 5.respond_to? :to_f #=> true |
Update, a respond to readers comments:
It’s true that you can do something like :
5.respond_to? "to_f" #=> true |
But what’s happening is that Ruby is casting it for you, but why to reserve extra memory to send it as a string?
For guys who are objecting on memory efficiency with symbols, I strongly recommend reading this post also.
I hope I could help you understand what Ruby symbols are and why they are used for, specially of you who are coming from other programing backgrounds.


Outstanding article it is surely. My friend has been waiting for this info.
I’ve been exploring for a little bit for any high quality articles or blog posts in this kind of house . Exploring in Yahoo I ultimately stumbled upon this web site. Reading this information So i am happy to exhibit that I’ve a very good uncanny feeling I found out just what I needed. I most undoubtedly will make certain to do not put out of your mind this site and provides it a look on a relentless basis.
It’s in point of fact a great and useful piece of info. I’m satisfied that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.
Hello, Neat post. There’s a problem with your site in web explorer, might check this… IE nonetheless is the marketplace leader and a good component of people will omit your great writing because of this problem.
Thank you for sharing superb informations. Your site is very cool. I’m impressed by the details that you have on this site. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for extra articles. You, my friend, ROCK! I found just the info I already searched everywhere and just could not come across. What a perfect web-site.
I was just seeking this information for some time. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this kind of informative websites in top of the list. Generally the top web sites are full of garbage.
Spot on with this write-up, I really think this website needs rather more consideration. I’ll probably be again to learn way more, thanks for that info.
The subsequent time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my option to learn, however I truly thought youd have something fascinating to say. All I hear is a bunch of whining about something that you may fix for those who werent too busy searching for attention.
I was reading some of your posts on this internet site and I think this site is very informative! Continue posting.
I just could not depart your site prior to suggesting that I extremely enjoyed the usual info a person provide to your guests? Is gonna be again often to check up on new posts.
Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is fantastic, as well as the content!. Thanks For Your article about Ruby symbols | Khelll's Blog .
I think other site proprietors should take this website as an model, very clean and magnificent user genial style and design, let alone the content. You’re an expert in this topic!
Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more clear from this post. I’m very glad to see such excellent information being shared freely out there.
Wonderful site. Lots of helpful info here. I’m sending it to a few pals ans also sharing in delicious. And obviously, thanks on your sweat!
Can I simply say what a aid to search out someone who actually is aware of what theyre speaking about on the internet. You undoubtedly know learn how to bring an issue to light and make it important. Extra people need to learn this and perceive this facet of the story. I cant imagine youre no more standard since you undoubtedly have the gift.
you may have a fantastic blog here! would you wish to make some invite posts on my weblog?
Good blog! I truly love how it is simple on my eyes and the data are well written. I am wondering how I could be notified whenever a new post has been made. I’ve subscribed to your RSS feed which must do the trick! Have a nice day!
Quite a few really legitimate factors! I appreciate you creating this post and also the rest of the blog is extremely wonderful also.
I found your weblog web site on google and check a number of of your early posts. Continue to maintain up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Looking for ahead to reading extra from you in a while!…
I simply had to thank you very much once more. I do not know the things I would’ve implemented in the absence of the entire thoughts documented by you on this question. Completely was an absolute hard matter for me, but considering a new professional style you dealt with that took me to leap with joy. I’m just grateful for your information and thus wish you really know what a powerful job you are accomplishing training most people with the aid of your websites. I know that you haven’t got to know all of us.
great points altogether, you just won a brand new reader. What would you suggest in regards to your post that you made some days in the past? Any positive?
I simply wanted to make a simple note to be able to say thanks to you for all the magnificent ideas you are placing here. My particularly long internet search has finally been rewarded with sensible tips to write about with my great friends. I ‘d suppose that we visitors actually are very endowed to dwell in a perfect site with so many marvellous professionals with great advice. I feel pretty fortunate to have used the website page and look forward to plenty of more amazing moments reading here. Thanks again for everything.
I must show my thanks to this writer just for bailing me out of such a dilemma. Just after scouting throughout the search engines and meeting principles which were not productive, I believed my life was over. Being alive devoid of the answers to the difficulties you have solved as a result of the blog post is a critical case, as well as the ones which could have negatively affected my career if I hadn’t discovered your web blog. Your own personal capability and kindness in handling every aspect was important. I don’t know what I would’ve done if I had not come upon such a point like this. I can at this moment look ahead to my future. Thanks for your time so much for this professional and results-oriented guide. I will not be reluctant to endorse your site to anybody who ought to have direction on this problem.
hello dudes!! Super site!
What’s Going down i am new to this, I stumbled upon this I have found It absolutely helpful and it has helped me out loads. I hope to give a contribution & assist other users like its helped me. Good job.
I intended to create you this bit of remark in order to thank you very much yet again considering the lovely solutions you have discussed in this article. This is certainly shockingly open-handed with you in giving freely just what many individuals could possibly have offered for an e-book in making some dough for their own end, and in particular considering that you could have tried it in the event you decided. The strategies likewise served to become fantastic way to be aware that other people online have similar eagerness really like my very own to see a whole lot more when it comes to this problem. Certainly there are millions of more enjoyable times in the future for many who check out your site.
Thanks for the sensible critique. Me & my neighbor were just preparing to do some research on this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such wonderful info being shared freely out there.
That is the suitable weblog for anybody who wants to search out out about this topic. You notice so much its almost onerous to argue with you (not that I actually would need…HaHa). You positively put a brand new spin on a subject thats been written about for years. Great stuff, just nice!
F*ckin’ remarkable things here. I am very glad to see your article. Thank you so much and i am taking a look ahead to touch you. Will you kindly drop me a e-mail?
Attractive part of content. I simply stumbled upon your website and in accession capital to say that I get in fact loved account your weblog posts. Anyway I will be subscribing for your feeds and even I achievement you get entry to persistently fast.
Very nice blog thanks alot for sharing your wisdom
Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, as well as the content!. Thanks For Your article about Ruby symbols | Khelll's Blog .
Ruby symbols | Khelll's Blog I was recommended this blog by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my problem. You’re amazing! Thanks! your article about Ruby symbols | Khelll's BlogBest Regards Cassetta
Oh my goodness! a tremendous article dude. Thank you However I am experiencing concern with ur rss . Don’t know why Unable to subscribe to it. Is there anybody getting identical rss drawback? Anybody who is aware of kindly respond. Thnkx
It is definitely a great and useful bit of information. I’m gratified that you just shared this useful info along with us. Please stay up-to-date similar to this. Thanks for sharing.
I wonder what % symbol really does.
First, I thought it was for Division but when I type in:
irb:005:0> 5 % 10
=> 5
Anyone can explain this? I am just a beginner.