Convert string to symbol-able in ruby

后端 未结 7 1918
天涯浪人
天涯浪人 2020-12-22 15:41

Symbols are usually represented as such

:book_author_title

but if I have a string:

\"Book Author Title\"

相关标签:
7条回答
  • 2020-12-22 16:23

    In Rails you can do this using underscore method:

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

    The simpler code is using regex (works with Ruby):

    "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
    => :book_author_title
    
    0 讨论(0)
  • 2020-12-22 16:29

    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 ;)

    0 讨论(0)
  • 2020-12-22 16:37

    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
    
    0 讨论(0)
  • 2020-12-22 16:37

    intern → symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist

    "edition".intern # :edition
    

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

    0 讨论(0)
  • 2020-12-22 16:41

    Is this what you're looking for?:

    :"Book Author Title"
    

    :)

    0 讨论(0)
  • 2020-12-22 16:41

    This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.

    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}
    

    Hope it helps someone like me!

    0 讨论(0)
提交回复
热议问题