自 Ruby 1.9 起,散列保证保留插入顺序,因此迭代顺序是明确定义的。 如何获取哈希中元素的索引?
例如,如果我有
footnotes = { "apple" => "is a fruit", "cat" => "is an animal", "car" => "a transport"}
我怎样才能得到这些的索引?,比如:
footnotes["cat"].index
# => 1
无需先检索密钥:
footnotes.find_index { |k,_| k== 'cat' } #=> 1
关于哈希键值对是否有索引(自 v1.9 起)的问题,我只想指出 Ruby 僧侣决定为我们提供 Enumerable#find_index,这当然意味着
Hash.instance_methods.include?(:find_index) #=> true
。
你可以做
footnotes.to_a.index {|key,| key == 'cat'}
# => 1