将string转换为ruby符号

符号通常是这样表示的

:book_author_title 

但如果我有一个string:

 "Book Author Title" 

有没有在rails / ruby​​的内置方式将其转换为符号,我可以使用:符号,而不只是做一个原始的string正则expression式replace?

Rails得到了提供这种方法的ActiveSupport::CoreExtensions::String::Inflections模块。 他们都值得一看。 举个例子:

 'Book Author Title'.parameterize.underscore.to_sym # :book_author_title 

来自: http : //ruby-doc.org/core/classes/String.html#M000809

 str.intern => symbol str.to_sym => symbol 

返回与str相对应的符号,如果之前不存在则创build该符号。 请参阅Symbol#id2name

 "Koala".intern #=> :Koala s = 'cat'.to_sym #=> :cat s == :cat #=> true s = '@cat'.to_sym #=> :@cat s == :@cat #=> true 

这也可以用来创build不能用:xxx表示法表示的符号。

 'cat and dog'.to_sym #=> :"cat and dog" 

但对于你的例子…

 "Book Author Title".gsub(/\s+/, "_").downcase.to_sym 

应该去 ;)

 "Book Author Title".parameterize('_').to_sym => :book_author_title 

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

parameterize是一个rails方法,它可以让你select你想要的分隔符。 这是默认的“ – ”。

intern→symbol返回str对应的Symbol,如果之前不存在则创build该符号

 "edition".intern # :edition 

http://ruby-doc.org/core-2.1.0/String.html#method-i-intern

在Rails中,你可以使用underscore方法来做到这一点:

 "Book Author Title".delete(' ').underscore.to_sym => :book_author_title 

简单的代码是使用正则expression式(适用于Ruby):

 "Book Author Title".downcase.gsub(/\s+/, "_").to_sym => :book_author_title 

这是你在找什么?

 :"Book Author Title" 

🙂