Splitting a symbol, in the same manner as one would split a string

故事扮演 提交于 2019-12-12 09:25:58

问题


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?


回答1:


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]



回答2:


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



来源:https://stackoverflow.com/questions/16437931/splitting-a-symbol-in-the-same-manner-as-one-would-split-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!