2009-11-25 73 views
0

这可能是非常明显的,但我找不到答案。如何从命名顺序获得整数索引

如何从命名为了得到整数索引,如:

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

有内置在Ruby或者Rails的做这个事情?

谢谢。

更新

感谢您的答复。这是我去的解决方案:

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

但是数组只支持到第五,所以它将被限制在那。

回答

0

我通常保留一个散列键数组来维护顺序。

0

您使用的是哪个版本的Ruby?对于Ruby 1.8,你不能这样做,因为在这个版本中,散列是一个无序的集合。这意味着当您插入密钥时,订单不会被保留。在迭代散列时,可能会以与插入顺序不同的顺序返回键。

虽然在Ruby 1.9中已经改变了。

+1

虽然这是Ruby 1.8真实的,它在Ruby 1.9中已经改变。哈希在Ruby 1.9中保留了插入顺序。对不起,挑剔:) – mtyaka 2009-11-25 21:05:19

+0

不,谢谢你的有用信息!我会更新该帖子以保持正确。 – 2009-11-25 21:09:17

0

调查Hash,其中混合Enumerable
我觉得each_with_index是你要搜索的内容:

# 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} 
1

如果您需要的顺序设置指标,你可能需要将阵列相结合,具有

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

以上方法只能工作在1.9但是。