Using Symbol name in Ruby
Symbols are an integral part of Ruby… we use them everyday. However sometimes they can be used for identification where we use their stringified version for comparison.
input = “wasabi”
:wasabi.to_s == input
=> true[[]]
Every time we do this, a new string is allocated in memory as the representation of :wasabi
. For a trivial example like this, it’s not a big deal but consider how often Ruby on Rails uses symbols (HashWithIndifferentAccess
anyone?). Then the bloat becomes very real.
Introduced in Ruby 3.0, Symbol#name(https://github.com/ruby/ruby/pull/3514) aims to help. Utilizing this method returns a frozen string version of the symbol.
:wasabi.name
=> “wasabi”
This looks like we’re reproducing the same result and in a way we are. However due to the returned string being frozen, there is only one immutable instance of it being used in memory!
It can be used the same way as well now with less memory bloat.
input = “wasabi”
:wasabi.name == input
=> true
Tweet