拆分符号,与拆分字符串的方式相同 [英] Splitting a symbol, in the same manner as one would split a string

查看:31
本文介绍了拆分符号,与拆分字符串的方式相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不先将符号转换为字符串的情况下拆分符号?例如,我试过

Is it possible to split a symbol without first converting it to a string? For example, I've tried

:split_this.split("_")

它只返回一个错误.我已经浏览了 Symbol 类参考,但所有示例都使用 to_s 将其转换为字符串.

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?

推荐答案

自从 Ruby 1.9 以来,一些字符串的特性被添加到 Symbol 类中,但没有那么多.你能做的最好的,我认为是:

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)

您可以将其转换为 Symbol 方法:

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]

这篇关于拆分符号,与拆分字符串的方式相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆