符号通常表示为
:book_author_title
但如果我有一个字符串:
"Book Author Title"
在rails / ruby中是否有内置方式将其转换为符号,我可以使用:
表示法而不仅仅执行原始字符串正则表达式替换?
答案 0 :(得分:333)
Rails获得了提供此类方法的ActiveSupport::CoreExtensions::String::Inflections
模块。他们都值得一看。以你的例子:
'Book Author Title'.parameterize.underscore.to_sym # :book_author_title
答案 1 :(得分:219)
来自:http://ruby-doc.org/core/classes/String.html#M000809
str.intern => symbol
str.to_sym => symbol
返回与str
对应的符号,如果之前不存在,则创建符号。请参阅Symbol#id2name
。
"Koala".intern #=> :Koala
s = 'cat'.to_sym #=> :cat
s == :cat #=> true
s = '@cat'.to_sym #=> :@cat
s == :@cat #=> true
这也可用于创建无法使用:xxx
表示法表示的符号。
'cat and dog'.to_sym #=> :"cat and dog"
但是你的例子......
"Book Author Title".gsub(/\s+/, "_").downcase.to_sym
应该去;)
答案 2 :(得分:21)
"Book Author Title".parameterize('_').to_sym
=> :book_author_title
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
parameterize是一个rails方法,它允许您选择分隔符的内容。默认情况下它是“ - ”。
答案 3 :(得分:13)
实习生→符号 返回与str对应的Symbol,如果以前不存在则创建符号
"edition".intern # :edition
答案 4 :(得分:10)
在Rails中,您可以使用underscore
方法执行此操作:
"Book Author Title".delete(' ').underscore.to_sym
=> :book_author_title
更简单的代码使用正则表达式(与Ruby一起使用):
"Book Author Title".downcase.gsub(/\s+/, "_").to_sym
=> :book_author_title
答案 5 :(得分:10)
这就是你要找的东西吗?:
:"Book Author Title"
:)
答案 6 :(得分:0)
这本身并不能回答问题,但是我发现这个问题是在寻找将字符串转换为符号并将其用于哈希的解决方案。
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
希望它可以帮助像我这样的人!