如何在ruby哈希中获取密钥的索引?

Jav*_*ini 3 ruby hash

如果我有

footnotes = { "apple" => "is a fruit", "cat" => "is an animal", "car" => "a transport"}
Run Code Online (Sandbox Code Playgroud)

我如何得到这些的索引?,如:

footnotes["cat"].index
# => 1
Run Code Online (Sandbox Code Playgroud)

Car*_*and 7

无需先检索密钥:

footnotes.find_index { |k,_| k== 'cat' } #=> 1
Run Code Online (Sandbox Code Playgroud)

至于散列键值对是否有索引的问题(自v1.9起),我只想指出Ruby僧侣决定向我们提供Enumerable#find_index,这当然就是这个意思Hash.instance_methods.include?(:find_index) #=> true.


San*_*osh 4

你可以做

footnotes.to_a.index {|key,| key == 'cat'}
# => 1
Run Code Online (Sandbox Code Playgroud)