Topic: Sort output from a hash ?

I've been using <%= debug(@session.data) -%> to display my session variables at the bottom of each screen while I'm writing a system. 

I now have about 15 variables and it's hard to find the one I want as they aren't in alphabetical order.  So I thought I'd just sort them so I can see them more easily.  So this is the code so far - which doesn't work.

<% @session.data.keys.sort.each do |key| %>
<%= key + @session.data[key] %>
<% end %>

I get the error - can't convert nil into Array - on the second line.

Is it because the values in the value part of the pair are strings as well as numbers?  All the examples in the Pickaxe book are only with numbers?

How can I do this?

Re: Sort output from a hash ?

After much experimenting, I've got something that displays the session variables alphabetically in a neat table!

<% session_array = session.data.to_a.sort_by {|key, value| key.to_s} %>

<table border="3">

    <tr><th colspan="2" bgcolor="#9dd05b">Session Variables</th></tr>
    <% session_array.each do |row| %>
        <tr><% row.each do |col| %>
                <td bgcolor="#fffbc6"><%= "#{col}" %>&emsp;</td>
            <% end %></tr>
    <% end %>

</table>


I'm not totally clear how it works - but it looks good!

Last edited by mikeb (2007-05-30 11:47:25)