Creating a table in HTML with Ruby?

2019-05-21 21:28发布

问题:

I am trying to make a table with ten values across on each row starting at 1 and going to 100.

My Ruby code looks like this:

<table border="1">

  <% (1..100).each do |i| 
    d3 = (i % 3 == 0) 
    d5 = (i % 5 == 0)

    i = "<b>#{i}</b>" if d5
    i = "<i>#{i}</i>" if d3 %>

    <tr>
      <td><%= i %></td>
    </tr>

  <% end %>
</table>

How would I put this in an HTML table in a 10 X 10?

回答1:

<table border="1">

<% (1..100).each do |i| 
   d3 = (i % 3 == 0) 
   d5 = (i % 5 == 0)

   s = "#{i}"
   s = "<b>#{i}</b>" if d5
   s = "<i>#{i}</i>" if d3 %>

  <% if i % 10 == 1 %><tr><% end %>
    <td><%= s %></td>
  <% if i % 10 == 0 %></tr><% end %>

<% end %>
</table>

Basically, you want to start a table row before elements 1, 11, 21, etc. and end a row after elements 10, 20, 30, etc.



回答2:

Using ERB:

<table>
<%10.times do |row|%>
  <tr>
    <%10.times do |col|%>
      <td><%=
        i = row*10+col+1
        if i%5==0
          "<b>#{i}</b>"
        elsif i%3==0
          "<i>#{i}</i>"
        else
          i
        end
      %></td>
    <%end%>
  </tr>
<%end%>
</table>

Using Haml:

%table
  - 10.times do |row|
    %tr
      - 10.times do |col|
        %td
          - i = row*10+col+1
          = i%5==0 ? "<b>#{i}</b>" : i%3==0 ? "<i>#{i}</i>" : i