Convert a Rails Ready Select Input Array to a Hash

March 23rd, 2011

This post explains a simple code snibbet I use convert a Rails-ready select input array into a hash.

The Rails-Ready Select Input Array

PRIVACY_LEVELS = [ ["Private",10], ["Community",20], ["Public",30] ]

The above code is a constant defined as an array with three elements, and each element is itself an array. Rails can use this to construct an HTML select input - sweet!

What if I want to access the first element of each sub-array?

I can do that! I create a new method in a helper that does the conversion for me:

  def privacy_hash
    Hash[ *PRIVACY_LEVELS.flatten].invert

This is a quality Ruby code expressiveness example!

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022