First, a trick. If you want to display a comma separated list from an array all you need to do is multiply that array by a comma. “What’s that”, you say? You heard right. If you have an array in the variable @my_array you can simply place the following in your view:
- <%= @my_array * ", " %>
<%= @my_array * ", " %>
The comma and space in your string will be added to the end of every string in your array except for the last one. Beautiful! I love rails.
Now for the reason for my post. While I’ve known this little trick for a while, I came across the need to titleize the outcome because my array contained all lowercase strings and I wanted to diplay them as titles.
It took a little trial and error, but the solution is rather simple:
- <%= (@my_array * ", ").titleize %>
<%= (@my_array * ", ").titleize %>
To apply the titleize method, you simply wrap your multiplication is parenthesis and add the .titleize as you normally would.
(Note: I still have not upgraded to Rails 2.0, so I cannot guarantee any of this will work in newer versions)







2 Responses to “Titleize an Array List in Rails”