Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range with leading zero in ruby

I have a form where my users can register to my site.

They fill in theirs birthdate in the form: birthyear, birthmonth and birthday.

So I am using Range to create the select in the form like this:

= f.select(:birthmonth, options_for_select((1..12)))

But that doesn't start the single digit numbers with a zero like i want: 01, 02, 03, 04, 05, 06, 07, 08, 09, 10 and so on..

I have even tried this but it didn't work:

= f.select(:birthmonth, options_for_select((01..12)))

Anybody that know how to get Range to start with leading zeros? Or any other way to do this so I can use it in the validation?:

validates_inclusion_of :birthmonth, :in => 1..12
like image 417
Lisinge Avatar asked Apr 21 '10 18:04

Lisinge


3 Answers

You can actually just do: '01'..'12'

like image 122
pguardiario Avatar answered Nov 18 '22 22:11

pguardiario


The trouble is that numbers themselves don't have leading zeroes (or, alternately, have an infinite number of leading zeroes that are never printed). To get leading zeroes, you need strings. Fortunately, Ruby comes with this sort of string formatting ability built in.

= f.select(:birthmonth, options_for_select((1..12).map {|n| "%02d" % n}))

The %02d is a formatting specifier that means "pad it with leading zeroes if it's less than two digits."

For validation, you'll need to do the same conversion:

validates_inclusion_of :birthmonth, :in => (1..12).map {|n| "%02d" % n}

(Thanks to @r-dub for pointing out that bit.)

like image 43
Chuck Avatar answered Nov 18 '22 23:11

Chuck


If it is just a presentational issue, you can construct [text, value] pairs and pass them to options_for_select:

Given a container where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and the "firsts" as option text.

So, something like:

options_for_select((1..12).map {|n| ["%02d" % n, n]})

That way you should be able to keep your validation logic as is.

like image 2
Mladen Jablanović Avatar answered Nov 18 '22 21:11

Mladen Jablanović