views:

22

answers:

3

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!

+5  A: 

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"
Chris
"this_is_an_example".classify = ThisIsAnExample
Bohdan Pohorilets
+1  A: 

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

John
+2  A: 

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"

Ashwin Phatak