Convert string to symbol-able in ruby
Rails got ActiveSupport::CoreExtensions::String::Inflections
module that provides such methods. They're all worth looking at. For your example:
'Book Author Title'.parameterize.underscore.to_sym # :book_author_title
from: http://ruby-doc.org/core/classes/String.html#M000809
str.intern => symbol
str.to_sym => symbol
Returns the Symbol corresponding to str
, creating the symbol if it did not previously exist. See Symbol#id2name
.
"Koala".intern #=> :Koala
s = 'cat'.to_sym #=> :cat
s == :cat #=> true
s = '@cat'.to_sym #=> :@cat
s == :@cat #=> true
This can also be used to create symbols that cannot be represented using the :xxx
notation.
'cat and dog'.to_sym #=> :"cat and dog"
But for your example ...
"Book Author Title".gsub(/\s+/, "_").downcase.to_sym
should go ;)
"Book Author Title".parameterize('_').to_sym
=> :book_author_title
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
parameterize is a rails method, and it lets you choose what you want the separator to be. It is a dash "-" by default.