4

I am rendering a variable in rails view.

<%= @data.matrix %>

which prints multidimensional array in template like this:

[[":23", ":12"],[ ":56", ":12"],[":21", ":23"]]

How can I represent the above data in table format that it will actually look like a matrix in view.html page for better reading the values row and colum. We also have the information of @data.row and @data.col in view template.

This is more HTML question but is there any way to do it with rails view syntax?

2 Answers 2

2

You could do something like:

<table>
  <% JSON.parse(@data.matrix).each do |tuple| %>
    <tr>
      <% tupel.each do |value| %>
        <td><%= value %></td>
      <% end %>
    </tr>
  <% end %>
</table>
4
  • Thanks for your answer. It's throwing an error undefined method each' for #<String:0x007fef3fb40998>` That means string is not null
    – Evil1989
    Commented Jul 1, 2015 at 1:55
  • So @data.matrix returns a string and not an array. Looks like JSON, therefore let's parse it as JSON first. Please see my updated answer. Commented Jul 1, 2015 at 2:02
  • I tried but it's only printing the arr[i][0] ..arr[i][col] value. Please have a look at the screenshot.i.imgur.com/pSFWuI0.png JSON representation of printing matrix section
    – Evil1989
    Commented Jul 1, 2015 at 2:11
  • You did not tell in your question that each sub-array has more that two values... Updated my answer again. Commented Jul 1, 2015 at 2:21
0

You could do something like for multiple array,

<table>
  <% @data.matrix.flatten.each do |value| %>
    <tr>
      <td><%= value %></td>
    </tr>
  <% end %>
</table>

Not the answer you're looking for? Browse other questions tagged or ask your own question.