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

4 Comments

Thanks for your answer. It's throwing an error undefined method each' for #<String:0x007fef3fb40998>` That means string is not null
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.
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
You did not tell in your question that each sub-array has more that two values... Updated my answer again.
0

You could do something like for multiple array,

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

Comments

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.