0

I'm trying to display values from array as table format

@array = {"Very Good"=>24, "Good"=>81, "Regular"=>3, "Bad"=>1, "Very Bad"=>1}

I have this array displaed but i want to display information as table format

<table>
  <tr>
     <td>Name</td>
     <td>Count</td>
  </tr>
  <% @array.each do |info|%>
  <tr>
    <td><% info[0].try("name") %></td>
    <td><% info[0].try("count") %></td>
  </tr>      
  <% end %>
</table>

I tried this code but it's displaying the information as row and i want to display values separated.

<% @array.map do |info| %>
 <%=  info %>
<% end %>

Here is the view display but i'm trying to display as table format (organized) with column name and column count.

<%= @array.tally %>

It displays with brackets:

{"Very Good"=>24, "Good"=>81, "Regular"=>3, "Bad"=>1, "Very Bad"=>1}  
2
  • It seems you're mixing up stuff here; it looks like you want to go over the pairs of keys -> values, but don't have a clear idea of how they're structured. Have you taken a look at Hash#to_a? Commented Jun 16, 2022 at 1:33
  • 1
    @array = { ... } – despite the variable name, that's a hash. Commented Jun 16, 2022 at 7:42

2 Answers 2

3
<table>
  <tr>
     <td>Name</td>
     <td>Count</td>
  </tr>
  <% @array.each do |key, value|%>
  <tr>
    <td><%= key %></td>
    <td><%= value %></td>
  </tr>      
  <% end %>
</table>

you also forgot the = to display the data <%= not <%.

Sign up to request clarification or add additional context in comments.

1 Comment

just a last question how can i order by key asc?
2

#When iterating over hashes, two placeholder variables are needed to represent each key/value pair.

@array = {"Very Good"=>24, "Good"=>81, "Regular"=>3, "Bad"=>1, "Very Bad"=>1}

@array.each do |key, value|
   p key // "Very Good, Good, Regular, Bad, Very Bad
   p value // 24,81, 3, 1, 1
end

enter image description here

Sort by with hash with value sort_by{|k, v| v}. If you sort with key, you can change sort_by{|k, v| k}

sortASC = Hash[@array.sort_by{|k, v| v}]
sortDESC =  Hash[@array.sort_by{|k, v| v}.reverse]

enter image description here

2 Comments

just a last question how can i order by key asc?
Well i was trying to get a solution without hash just using each do

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.