Converting an Array to a Hash

Hi Becca, it looks like this shouldn’t be to bad to convert over…

A hash requires two values for every entry, a key and a value for that key, keeping this in mind…

  1. def generate_sub_nav

  2. sub_nav_hash = Hash.new
    
  3.   user = User.find(session[:user])
    
  4.   for role in user.roles
    
  5.     for right in role.rights
    
  6.       if right.on_menu
    
  7.         sub_nav_hash[:Key_Goes_Here] = right.action
    
  8.       end
    
  9.     end # for right
    
  10.   end # for role
       # The below line won't work, Hashes don't sort!, but you can still iterate through them
    
  11.  #sub_nav_array.sort!
    
  12. end # def

  13. for menu in menu_items html_out = Hash.new

  14. html_out[:Key_Goes_Here] = link_to_unless_current (menu,

  15.     :controller => menu,
    
  16. :action => menu)

  17. end

That should give you an idea of what you can do there… The nice thing about hashes is that if the key you put in place of “:Key_Goes_Here” doesn’t exists it is still treated like it does and assigned a value appropriately… The other thing is that when accessing a Hash if a Key you try to get a value for doesn’t exist then the hash return nil… Keep those in mind while you code :slight_smile: Other than that you just have to figure out what you want your key to be named and you should be good to go… since its a loop if you have an associated string or something to go with that value you could dump that in for the key. Oh, and you don’t have to use Hash.new you can also just do:

html_out = {}

And I believe that will get you the same result… Good luck and happy coding!

Unfortunately, this is where I run into a snag… I haven’t used the helper files yet as most of my application wide functions just go directly into application.rb… The helper files tend to just provide additional functionality to the templates from what I’ve read though, so you might have to move that code into controllers, there might yet be a way to do it though, unfortunately I don’t know how :frowning: