-->

分割一个符号,以相同的方式作为一个将分割的字符串(Splitting a symbol, in th

2019-09-02 06:12发布

是否有可能分裂的象征,而不首先将其转换为字符串? 举例来说,我已经试过

:split_this.split("_")

而且只返回一个错误。 我通过看标志类的引用 ,但所有的示例用to_s把它转换为字符串。

我知道我可以将其转换为字符串,将它和两个子转换为符号,但只是似乎有点麻烦。 有没有更优雅的方式来做到这一点?

Answer 1:

由于Ruby 1.9的一些字符串的功能被添加到Symbol类,但不是这个much.The你能做到最好,我认为是:

:symbol_with_underscores.to_s.split('_').map(&:to_sym)

你可以变成这个Symbol方法:

class Symbol
  def split(separator)
    to_s.split(separator).map(&:to_sym)
  end
end

:symbol_with_underscores.split('_')
# => [:symbol, :with, :underscores]


Answer 2:

想想符号数字。 因为符号被内部存储为INT号码 。 因此,他们没有字符串相关的方法。



文章来源: Splitting a symbol, in the same manner as one would split a string