I have a hash of strings
navigable_objects = { 'Dashboard' => root_path,
'Timesheets' => timesheets_path,
'Clients' => clients_path,
'Projects' => projects_path,
}
I want to convert them into another hash where the key is again the key, but the value is either the string ‘active’ or empty string depending on whether the current controller name contains the key.
For example, lets say that the current controller name is “ClientsController”. The result I should get is:
{ 'Dashboard' => '',
'Timesheets' => '',
'Clients' => 'active',
'Projects' => ''
}
Here is how I am currently doing it:
active = {}
navigable_objects.each do |name, path|
active[name] = (controller.controller_name.include?(name)) ? 'active' : '')
end
I feel that while this works, there is a better way to do this in Ruby, possibly using inject or each_with_objects?
NOTE: I already answered but I’m posting this as a separate answer because it’s better for your specific situation, but my other answer still has merit on its own.
Since you’re not using the values of the hash at all, you can use
each_with_object:Or more verbosely:
If your result was based on the values too, then my other solution would work whereas this one wouldn’t.