Rails select options

written by justin on August 24th, 2007 @ 03:48 PM

I am developing an application where I have a dropdown list of hours worked on a project. The spec is that it should be in quarter hour increments using a decimal notation. So, 0, 0.25, 0.50, 0.75, etc. The select helper in rails takes an array of arrays that would look like this: [[0,0],[.25,.25], etc...]. I needed to generate that array and this is what I came up with:

  def labor_hours
    ar = []
    (0..39).each do |n| 
    	a = n.to_f
    	b = a + 0.25
    	c = a + 0.50
    	d = a + 0.75
    	ar.push([sprintf('%0.2f', a), a],[sprintf('%0.2f', b), b],[sprintf('%0.2f', c), c],[sprintf('%0.2f', d), d])
    end
    ar.push(["40.00",40])
  end

I start by creating the array that I'm going to return. I then use a range and a block to loop over 0 to 39. I have to made sure that I convert the integers to floats and add my partial hours. I then create my arrays for this integer and add them to the final array. At the last second, I add the last array for a nice even 40 hours. Works pretty well. I used sprintf to format the floats so that everything has 2 decimal places instead of some with one and some with two.

So, my view code looks like this:

<%= form.select 'labor', labor_hours, :include_blank => true %>

Comments are closed