Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Jul 01

Ruby on Rails & Maths...

Posted by Annalisa Afeltra in Ruby on Rails - 5 comments digg this add to delicious

I have always been fascinated with Mathematics and how you can solve problems using it, we all know that in programming it is very useful. I recently had to use maths in a layout that I needed to incorporate for a new application…

Problem:

I had to display a dynamic list of suburbs in a table, that was an x amount of rows and had 3 columns.

Solution:

I used Mod (the mathematical arithmetic that gives you the remainder of the division).

Therefore:


<table>
<% r = 0 %>
<% @count_suburb.each do |c| %>
<% area = Area.find_by_code(c[0])%>

<% if ((r % 3) == 0)  %>
<tr>
<% end %>
<% r += 1%>

<td>Write something here....<%= c.name.capitalize  %></td>

<% if ((r % 3) == 0)  %>
</tr>    
<% end %>

<% end %>
</table>

Does anyone know of a better solution?

Thanks Annalisa

Comments

  • Dmytro Shteflyuk

    Posted on July 01

    
    a=['a','b','c','d','e','f','g','h','i','k']
    a.in_groups_of(3, false) do |row|
      puts '<tr>'
      row.each { |el| puts '<td>%s</td>' % el }
      puts '</tr>'
    end
    
  • Dmytro Shteflyuk

    Posted on July 01

    Here is snippet for your code example:
    
    <% @count_suburb.in_groups_of(3, false) do |row| %>
      <tr>
        <% row.each do |c| %>
          <% area = Area.find_by_code(c[0])%>
          <td>Write something here....<%= c.name.capitalize  %></td>
        <% end %>
      </tr>
    <% end %>
    
  • Aris

    Posted on July 01

    Look into the group_by method. You can ask it to give items in groups of three
  • Annalisa

    Posted on July 01

    Hi Dmytro, Thanks so much, that is a great help, much easier to read and looks much better.
  • Christoph Olszowka

    Posted on July 02

    You're gonna run into some layout problems with missing TDs in the last row when having mulitple rows though if the total suburb count % 3 is not 0. You can give in_groups_of some other default item, preferably Suburb.new(:name => ""), which will also have the name attribute and the capitalize method can be applied to the empty string given. http://rails-doc.org/docs/ActiveSupport/CoreExtensions/Array/Grouping/in_groups_of

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory