Sorting a hash in a view

I should be able to figure this out but perhaps I am brain dead…

I simply want to display the next id in sequence for a few ‘categories’.

My view template is very basic…

<% for next_seq in @next_seq %>
<%= next_seq[0] %> - <%= next_seq[1] %>

<% end %>

and I want them sorted in next_seq[0] order and since @next_seq is a
hash, it displays in a rather random order.

Not that this should matter, but the controller code for this looks like
this…

@lib_cat = Valuelist.find(:all,
  :conditions => ["list_name = 'Library Categories'"],
  :order => 'list_value')
@next_seq = Hash.new
for lib_cat in @lib_cat
  @next_seq[lib_cat.list_value] = Library.find(:first,
    :conditions => ['ltype = ?', lib_cat.list_value],
    :order => 'id DESC').id + 1
end

I’m not doing a ‘select’ so I can’t do the normal collect_for_selection
thingy

Craig

Hashes don’t have an order. The keys come out through iterators in a
psuedo random order no matter what. If you want to keep them in order,
you have to use an array. You can event make it an array of hashes if
you like.

On 11/18/06, Craig W. [email protected] wrote:

<% end %>
@next_seq = Hash.new
for lib_cat in @lib_cat
@next_seq[lib_cat.list_value] = Library.find(:first,
:conditions => [‘ltype = ?’, lib_cat.list_value],
:order => ‘id DESC’).id + 1
end

I’m not doing a ‘select’ so I can’t do the normal collect_for_selection
thingy

Rather than trying to force a hash to return a particular order, why not
just do what
options_for_select does - use an array of two-element arrays.
Your controller would look like this:

@lib_cat = Valuelist.find(:all,
:conditions => [“list_name = ‘Library Categories’”],
:order => ‘list_value’)
@next_seq = Hash.new
for lib_cat in @lib_cat
@next_seq << [lib_cat.list_value, Library.find(:first,
:conditions => [‘ltype = ?’, lib_cat.list_value],
:order => ‘id DESC’).id + 1]
end

(hardcore functional programmers can replace the for loop with an inject
for
their
own amusement…)

The view code would remain the same.


Matt J.
[email protected]
President/Technical Director, Acme Art Company (acmeartco.org)

On Sun, 2006-11-19 at 14:53 -0500, Matt J. wrote:

    My view template is very basic...
    looks like 
        end

(hardcore functional programmers can replace the for loop with an
inject for their
own amusement…)

The view code would remain the same.


yep - just had to replace

@next_seq = Hash.new
with
@next_seq = Array.new

Thanks

Craig

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs