Printing the alphabet easily in Ruby on Rails

Posted on 04 May 2006

It's really easy to print out the alphabet with Ruby. I needed to do recently as an additional method for searching by letter. Although, I could see it might be useful for pagination.

The code I used is as follows:

<ul>
  <% "A".upto("Z") do |l| -%>	    
     <li><%= link_to l, genre_letter_url(:letter => l) %></li>	
  <% end %>
</ul>

The key bit is "A".upto("Z") do |l|. Note that if you use lowercase letters then your output will be in lowercase.

If you are wondering about my use of genre_letter_url(:letter => l) This is best explained in my article about routes in ruby on rails and in particular named routes.

Comments left...

  • i like better

    
    ('A'..'Z').each do |l| ...
    

    na43251 at 01 Oct 07 at 22:02

  • Both works. Nice help buddies

    Nouman at 04 Sep 08 at 11:49

Got something to say?