crystal-langstring-to-symbol

Crystal language: what to use instead of runtime String::to_sym


I am trying to convert a Ruby program to Crystal.

And I am stuck with missing string.to_sym

I have a BIG XML file, which is too big to fit in memory.

So parsing it all is out of question. Fortunately i do not need all information, only a portion of it. So i am parsing it myself, dropping most of the lines. I used String::to_sym to store the data, like this:

:param_name1 => 1
:param_name2 => 11
:param_name1 => 2
:param_name2 => 22
:param_name1 => 3
:param_name2 => 33

What should I use in Crystal?

Memory is the bottleneck. I do not want to store param_name1 multiple times.


Solution

  • If you have a known list of parameters you can for example use an enum:

    enum Parameter
      Name1
      Name2
      Name3
    end
    
    a = "Name1"
    b = {'N', 'a', 'm', 'e', '1'}.join
    pp a.object_id == b.object_id # => false
    pp Parameter.parse(a) == Parameter.parse(b) # => true
    

    If the list of parameters is unknown you can use the less efficient StringPool:

    require "string_pool"
    
    pool = StringPool.new
    
    a = "param1"
    b = {'p', 'a', 'r', 'a', 'm', '1'}.join
    
    pp a.object_id == b.object_id # => false
    a = pool.get(a)
    b = pool.get(b)
    pp a.object_id == b.object_id # => true