Using one-dimensional arrays in select statements (noob)

I have an issue whereby I want the attributes on an object to be saved
in the db as simple integers and the corresponding labels to be stored
in the class.

DB Car:
id int, name varchar(10), speed int

Model Car:
class Car < ActiveRecord::Base
Speed = %w{Slow Normal Fast}
end

View Car:

Slow Normal Fast

What is the select statement to get the options to print out like that?
Now I know that I could set Speed to be a hash (Speed = {“slow”=>0,
“normal”=>1, “fast”=>2}) but then I would lose the ordering, which is
important. I could use an associative array as well (Speed = [[“Slow”,
0],[“Normal”, 1],[“Fast”, 2]]) but this Car object will have a number of
similar attributes so that would seem to violate the DRY principal
having to put 0, 1, 2, etc in every time.

Is there a way to print out a select statement using a simple
one-dimensional array with the item’s index value acting as the key in
the option tag?

I very much want to do this the Ruby way. Any help would be greatly
appreciated.

On 12/6/05, sean [email protected] wrote:

What is the select statement to get the options to print out like that?
Now I know that I could set Speed to be a hash (Speed = {“slow”=>0,
“normal”=>1, “fast”=>2}) but then I would lose the ordering, which is
important. I could use an associative array as well (Speed = [[“Slow”,
0],[“Normal”, 1],[“Fast”, 2]]) but this Car object will have a number of
similar attributes so that would seem to violate the DRY principal
having to put 0, 1, 2, etc in every time.

There isn’t a method that does exactly what you want, as far as I
know. But here’s an idea that is pretty good with regards to DRY:

class Array
def with_indexes
a = []
each_with_index {|x,i| a << [x,i]}
a
end
end

Model Car:
class Car < ActiveRecord::Base
@@speeds = %w{Slow Normal Fast}
cattr_reader :speeds
end

View Car:
select(“mycar”, “speed”, Car.speeds.with_indexes)

jeremyevans0 wrote:

There isn’t a method that does exactly what you want, as far as I
know. But here’s an idea that is pretty good with regards to DRY:

That is an excellent solution, thanks very much for your input on what
was a vexing issue.