Convert Inches to Feet and Inches

I love simple problems, such as fill a drop-down with a range of feet and inches.

One way to do it is to hand-code a <select> element and fill it with hand-coded <option> elements, but what’s the fun in that?

It’s more fun to iterate over an array (range) of integers representing inches, and do the math to convert those inches to feet and inches. To get feet, use the floor function, which truncates all decimal places without rounding. To get inches, use the modulus operator (the % operator) which returns the remainder. 36 is 3′0″ and 74 is 6′2″.

The math is the same but (as John Madden would say, if he were a programmer) the syntax varies by language… Here’s how you do it in Ruby:

<%= select :person,
       :height,
       (36..95).collect{|i|["#{(i/12).floor}' #{i%12}\"",i]},
       {:selected=>@person.height} %>

And here’s what you end up with:

And unformatted:

select :person, :height, (36..95).collect{|i|["#{(i/12).floor}' #{i%12}\"",i]}, {:selected=>@person.height}

Leave a Reply