This blog is part of our Ruby 3.0 series.
All are excited about what Ruby 3.0 has to offer to the Ruby developers. There is already a lot of buzz that the feature set of Ruby 3.0 will change the perspective of developers how they look at Ruby.
One of the important aspects of Ruby 3.0 is optimization. The part of that optimization is the introduction of name method for Symbol. In this blog, we will take a look at what name method of class Symbol does and why it was introduced. The new name method is introduced on Symbol to simply convert a symbol into a string. Symbol#name returns a string. Let's see how it works.
1 2irb(main):001:0> :simba.name 3=> 'simba' 4irb(main):002:0> :simba.name.class 5=> String 6irb(main):003:0> :simba.name === :simba.name 7=> true 8
Wait what? Don't we have to_s to convert a symbol into a string. Most of us have used to_s method on a Symbol. The to_s method returns a String object and we can simply use it. But why name?
Using to_s is okay in most cases. But the problem with to_s is that it creates a new String object every time we call it on a symbol. We can verify this in irb.
1 2irb(main):023:0> :simba.to_s.object_id 3=> 260 4irb(main):024:0> :simba.to_s.object_id 5=> 280 6
Creating a new object for every symbol to a string conversion allocates new memory which increases overhead. The light was thrown on this issue by schneems (Richard Schneeman) in a talk at RubyConf Thailand where he showed how Symbol#to_s allocation causes significant overhead in ActiveRecord. This inspired Ruby community to have a new method name on Symbol which returns a frozen string object. This reduces the string allocations dramatically which results in reducing overhead.
1 2irb(main):001:0> :simba.name.frozen? 3=> true 4irb(main):002:0> :simba.name.object_id 5=> 200 6irb(main):003:0> :simba.name.object_id 7=> 200 8
The reason to bring this feature was that most of the times we want a simple string representation for displaying purpose or to interpolate into another string. The result of to_s is rarely mutated directly. By introducing this method we save a lot of objects which helps in optimization. Now we know the benefits of name, we should prefer using name over to_s when we don't want to mutate a string.