Hashes for select

In Ruby on Rails there’s a very easy way to create a select tag:

form.select("period", [["Month", 1], ["Year", 12]])

In my case I have the options in a hash, like:

periods = {
  1 => "Month",
  12 => "Year"

but when I did this:

form.select("period", periods)

I was surprised to find out that the keys of the hash are used as the content of the options, and the values as the keys, producing this code:

<select id="resource_period" name="resource[period]">
  <option value="Month">1</option>
  <option value="Year">12</option>

Definitely not what I wanted, so I wrote this method:

class ApplicationController < ActionController::Base
  helper_method :hash_for_select

  def hash_for_select(hash, sort_by = :value)
    sort_by = sort_by == :value ? 0 : 1
    options = hash.map { |k, v| [v, k] }.sort { |x, y| x[sort_by]  y[sort_by] }

and now I can do

form.select("period", hash_for_select(periods))

if I want the options sorted by key value or

form.select("period", hash_for_select(periods, :key))

if I want them sorted by keys.

Closing tag in XML

I always wondered why they didn’t allow an optional closing tag of “</>” that would close the corresponding open tag.

For example:

<p>This is a string with something <b>bold</> in it.</p>

where “</>” is closing the <b> tag. Or:


which is shorter than:


I fell it is a shortcut like the stand-alone tag <tag/>.