views:

83

answers:

4

This might be really obvious but I can't find the answer.

How do you get the integer index from named order, like:

{ :first => 0, :second => 1, :third => 2, :fourth => 3 }

Is there something built in to Ruby or Rails that does this?

Thanks.

Update

Thanks for all your responses. Here's the solution I went with:

def index_for(position) 
  (0..4).to_a.send(position)
end

but arrays only support up to fifth, so it'll be limited to that.

A: 

I usually keep an array of hash keys to maintain order.

Tim
A: 

What version of Ruby are you using? For Ruby 1.8, you can't because in this version a hash is an unordered colletion. This means that when you insert keys, the order is not preserved. When you iterate over the hash, the keys might be returned in a different order from the order you inserted them.

It has changed in Ruby 1.9 though.

Mark Byers
While this is true for Ruby 1.8, it has changed in Ruby 1.9. Hash preserves insertion order in Ruby 1.9. Sorry for nitpicking :)
mtyaka
No, thanks for the useful information! I'll update the post to be correct.
Mark Byers
A: 

Look into Hash which mixes in Enumerable.
I think each_with_index is what you are searching for:

# Calls block with two arguments, the item and its index, for each item in enum. 

hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
  hash[item] = index
}
hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
Styggentorsken
+1  A: 

If you need the ordering index, you might need to combine the array and has

keys = [ :first, :second, :third, :fourth ]
hash = { :first => 0, :second => 1, :third => 2, :fourth => 3 }
hash.each_key { |x| puts "#{keys.index(x)}" }

The above method only work in 1.9 though.

DJ