Search code examples
rubystringsymbolsdigits

Symbolize any non-digit in String (Ruby)


I have the following string output:

"[1, 2, 3, *, +, 4, 5, -, /]"

How can I symbolize the non-digits characters (i.e. *, +, -, /) and return the following result:

[1, 2, 3, :*, :+, 4, 5, :-, :/]

Currently, I'm using this method to convert the string:

def tokens(str)
    new_str = str.split(/\s+/)
    clean_str = new_str.to_s.gsub(/"/, '')
            #Symbolise clean_str to desired output
end

Solution

  • str = "[1, 2, 3, *, +, 4, 5, -, /]"
    
    str.scan(/[^\[\]\s,]+/)
    # => ["1", "2", "3", "*", "+", "4", "5", "-", "/"]
    
    str.scan(/[^\[\]\s,]+/).map {|t| Integer(t) rescue t.to_sym }
    # => [1, 2, 3, :*, :+, 4, 5, :-, :/]