1

I have a real simple question here. I only want to know if there is an existing Rails way to accomplish this, because I don't want to re-write something that is already in the framework.

Think of an underscored variable name like "this_is_an_example". Is there a quick way to turn that into "This is an example" or even "This Is An Example" using Rails? I know ActiveRecord prints table column names like "first_name" as "First Name", how is it doing that?

Thanks!

3 Answers 3

5

The thing that already exists is called the Inflector. Check out the documentation at http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html.

All the methods listed there are new methods on Strings, so in your case:

st = "this_is_an_example"
st.humanize # => "This is an example"
st.titleize # => "This Is An Example"
1
  • "this_is_an_example".classify = ThisIsAnExample
    – Bohdan
    Aug 18, 2010 at 15:21
2

ruby script/console Loading development environment (Rails 2.3.8)

"this_is_an_example".titleize => "This Is An Example"

"this_is_an_example".humanize => "This is an example"

1

I should have looked a little harder for a solution before asking.

>> string = "an_example_string"
=> "an_example_string"
>> string.titleize
=> "An Example String"
>>

Find the docs for this here: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001058

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.