Is it possible to split a symbol without first converting it to a string? For example, I've tried
:split_this.split("_")
and it only returns an error. I've looked through the Symbol class reference, but all the example use to_s
to convert it to a string.
I know I can convert it to a string, split it, and convert the two substrings to symbols, but that just seems a bit cumbersome. Is there a more elegant way to do this?
Since Ruby 1.9 some string's features are added to the Symbol
class but not this much.The best you can do, I think is:
:symbol_with_underscores.to_s.split('_').map(&:to_sym)
You could turn this into a Symbol
method:
class Symbol
def split(separator)
to_s.split(separator).map(&:to_sym)
end
end
:symbol_with_underscores.split('_')
# => [:symbol, :with, :underscores]
Think about symbols as numbers. Because symbols are internally stored as int numbers. Therefore they don't have string related methods.