2

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?

2
  • 2
    FWIW, I don't like when the iterator variable is re-assigned in the block; I find that confusing to think about. Commented Jul 25, 2012 at 22:55
  • 2
    @DaveNewton It sure confused me -- I made (and fixed) two separate mistakes in my answer due to it. Commented Jul 25, 2012 at 22:58

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

I likely would have done the same thing in ERB (the ternary).
@Dave Well, yeah, I didn't want to blow the poor beginner's mind :)
You are a kind and benevolent Phrogz.
thanks, i only wish this wasnt way over my head. oh well, maybe i will understand it in a few weeks
If it's over your head just google the ruby topics that confuse you. The only things you might not understand yet are ternary and modulos operators. It should only take you minutes to understand it.
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.

3 Comments

+1 for using the OP's original 1-100 loop, even if this sort of ERB manual markup generation is exactly the sort of reason I prefer Haml these days.
@Phrogz Thanks! Yeah, if I were doing it myself, I'd prefer either of your solutions. As you said, not wanting "to blow the poor beginner's mind", I usually prefer to correct their code rather than rewrite it. I'm glad you demonstrated some more idiomatic and elegant styles.
@user102825 You're very welcome. Have fun, and welcome to Stack Overflow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.