LoginSignup
2

More than 5 years have passed since last update.

StringからSymbol

Posted at

"Book Author Title" みたいな文字列を
:book_author_title みたいなシンボルにしたい時。

'Book Author Title'.parameterize.underscore.to_sym

で出来る。

sample
  class Person
    def to_param
      "#{id}-#{name.parameterize}"
    end
  end

  @person = Person.find(1)
  # => #<Person id: 1, name: "Donald E. Knuth">

  <%= link_to(@person.name, person_path(@person)) %>
  # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

ActiveSupport::Inflectorモジュールは結構使いそうな感じなのが多いので、ちゃんと読む。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2