Skip to content

Instantly share code, notes, and snippets.

@danielsan
Last active March 27, 2018 17:52
Show Gist options
  • Save danielsan/ace7d027fd3503989a6024236783f514 to your computer and use it in GitHub Desktop.
Save danielsan/ace7d027fd3503989a6024236783f514 to your computer and use it in GitHub Desktop.
# creating a fake list
cities = ['Miami', 'Diadema', 'NYC', 'Sao Paulo']
fruits = ['Manana', 'Molango', 'Bacate', 'Acabaxi']
list = []
cities.each{|city| fruits.each{|fruit| list.push({city: city, product: fruit, count: rand(10..100)}) }}
puts list
# this will hold the crosstab
@myCities = {}
# this will hold the unique products for the header
@uniqProducts = {}
# Creating crosstab structure
list.each{|row|
cityName = row[:city]
productName = row[:product]
@uniqProducts[ productName ] = true;
# cria um hash vazio se aquela chave ainda nao existe
@myCities[ cityName ] = {} if @myCities[ cityName ].nil?
@myCities[ cityName ][ productName ] = row[:count]
}
<table>
<thead>
<tr>
<th>Cities</th>
<% @uniqProducts.keys.each do |productName| %>
<th><%= productName %></th>
<% end %>
</tr>
</thead>
<tbody>
<% @myCities.each_pair do |cityName, cityProducts| %>
<tr>
<th><%= cityName %></th>
<% @uniqProducts.keys.each do |productName| %>
<td><%= cityProducts[ productName ] %></td>
<% end #uniqProducts.keys %>
</tr>
<% end #myCities.each_with_keys %>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment