1

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?

toro2k
  • 19,020
  • 7
  • 64
  • 71

2 Answers2

3

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]
toro2k
  • 19,020
  • 7
  • 64
  • 71
3

Think about symbols as numbers. Because symbols are internally stored as int numbers. Therefore they don't have string related methods.

Community
  • 1
  • 1
Greg Dan
  • 6,198
  • 3
  • 33
  • 53
  • Actually symbols are often manipulated as strings in Ruby, think of ActiveRecord's dynamic finders for example. The core library itself defines some string methods for symbols i.e. `downcase`, `capitalize`. – toro2k May 08 '13 at 11:03
  • @toro2k Each subsequent **Rails** version has less of the magic. Moreover, overuse of string to symbol conversions led to [CVE-2013-1854 Symbol DoS vulnerability in Active Record](https://groups.google.com/forum/#!topic/ruby-security-ann/o0Dsdk2WrQ0) – Greg Dan May 08 '13 at 22:02